# @hakimio/ngx-google-analytics 中文文档

规范地址：https://npmcn.com/package/%40hakimio/ngx-google-analytics/

版本：15\.0\.0
npm 元数据更新时间：2023-10-03T09:37:51.520Z
中文译文更新时间：2026-11-17T06:29:39.585Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40hakimio/ngx-google-analytics
原文对照：https://npmcn.com/package/%40hakimio/ngx-google-analytics/?lang=original
项目主页：https://github.com/hakimio/ngx-google-analytics
源码仓库：https://github.com/hakimio/ngx-google-analytics

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：236 kB，59 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：@angular/common \>=16\.0\.0，@angular/core \>=16\.0\.0，@angular/router \>=16\.0\.0，rxjs ^7\.4\.0
- 首次发布：2023-10-03T09:37:50.989Z
- 最新版本发布：2023-10-03T09:37:51.231Z
- 近 30 天下载量：7260（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

Angular 应用程序的简单 Google 分析包

## 安装

```sh
npm install @hakimio/ngx-google-analytics
```

也可以使用：`pnpm add @hakimio/ngx-google-analytics`、`yarn add @hakimio/ngx-google-analytics`、`bun add @hakimio/ngx-google-analytics`

## README

# Ngx 谷歌分析

> 在 Angular apps 中追踪 GA4 事件的简单方法.

`@hakimio/ngx-google-analytics` 是一个叉子 **麦斯·安德里亚尼的** `ngx-google-analytics`。 。 。 .

# 指数

-   [设置](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-setup)
    -   [安装软件包](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-install-the-package)
    -   [独立](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-standalone-app-component)
    -   [NG 模块](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-ngmodule)
    -   [设置路由器提供者](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-setup-router-provider)
    -   [高级路由器提供者设置](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-advanced-router-provider-setup)
-   [谷歌分析服务](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-googleanalyticsservice)
    -   [注册分析事件](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-register-analytics-events)
    -   [人工注册页面浏览](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-manually-register-page-views)
-   [指令](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-directives)
    -   [简单的指令使用](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-simple-directive-usage)
    -   [输入元素的使用](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-usage-on-input-elements)
    -   [指令组](https://npmcn.com/package/%40hakimio/ngx-google-analytics/#readme-directive-groups)

## 设置

### 安装软件包

```
npm install @hakimio/ngx-google-analytics
```

### 独立应用程序组件

如果您的应用程序组件正在使用独立的 API, 请遵循这些步骤来设置库 :

-   添加 `provideGoogleAnalytics('ga4-tag-id')` 给你的应用程序的供应商。 如果您找不到您的 GA4 标记代号, 请看 [这个](https://support.google.com/analytics/answer/9539598?sjid=1584949217252276099-EU) Google帮助页面.

`main.ts`

```ts
import {AppComponent} from './app/app.component';
import {bootstrapApplication} from '@angular/platform-browser';
import {ROUTES} from './app/app.routes';
import {provideGoogleAnalytics} from '@hakimio/ngx-google-analytics';

bootstrapApplication(AppComponent, {
    providers: [
        provideRouter(ROUTES),
        provideAnimations(),
        provideGoogleAnalytics('ga4-tag-id') // ⬅️ Google Analytics provider
    ]
}).catch(err => console.error(err));
```

您还可以使用第二个可选参数指定额外的设置 : `provideGoogleAnalytics('ga4-tag-id', settings)`。 。 。 . 见 [IGoogle分析](https://github.com/hakimio/ngx-google-analytics/blob/master/projects/ngx-google-analytics/src/lib/interfaces/i-google-analytics-settings.ts) 界面,以获取更多关于可用设置的信息.

-   添加 `NgxGoogleAnalyticsModule` 到您的应用组件的导入 :

`app.component.ts`

```ts
import {NgxGoogleAnalyticsModule} from '@hakimio/ngx-google-analytics';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    standalone: true,
    imports: [
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ]
})
export class AppComponent {}
```

### NG 模块

如果你的申请是 `NgModule` 根据这些步骤建立图书馆:

-   添加 `NgxGoogleAnalyticsModule` 到您的根应用程序模块( e)`AppModule`(中文(简体) ) `imports`。 。 。 .
-   添加 `provideGoogleAnalytics('ga4-tag-id')` 在您的应用程序模块的提供者。 如果您找不到您的 GA4 标记代号, 请看 [这个](https://support.google.com/analytics/answer/9539598?sjid=1584949217252276099-EU) Google帮助页面.

`app.module.ts`

```ts
import {NgxGoogleAnalyticsModule, provideGoogleAnalytics} from '@hakimio/ngx-google-analytics';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id') // ⬅️ Google Analytics provider
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}
```

您还可以使用第二个可选参数指定额外的设置 : `provideGoogleAnalytics('ga4-tag-id', settings)`。 。 。 . 见 [IGoogle分析](https://github.com/hakimio/ngx-google-analytics/blob/master/projects/ngx-google-analytics/src/lib/interfaces/i-google-analytics-settings.ts) 界面,以获取更多关于可用设置的信息.

### 设置路由器提供者

如果您正在使用 Angular 路由器并想要跟踪页面视图, 您可以包含 `provideGoogleAnalyticsRouter()` 在您的根应用程序提供者中.

**关键是:** `provideGoogleAnalyticsRouter()` 与 SSR 不相容,不应包含在服务器应用程序供应商中.

```ts
import {NgxGoogleAnalyticsModule, provideGoogleAnalytics, provideGoogleAnalyticsRouter} from '@hakimio/ngx-google-analytics';

@NgModule({
    imports: [
        // ...
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id'),
        provideGoogleAnalyticsRouter() // ⬅️ Google Analytics router provider
    ]
})
export class AppModule {}
```

### 高级路由器提供者设置

您可以通过路由选项将一些路径包含或排除到 `provideGoogleAnalyticsRouter(options)`。 。 。 .

支持以下路径匹配 :

-   简单路径匹配 : `{ include: [ '/full-uri-match' ] }`· ;
-   通关卡路径匹配 : `{ include: [ '*/public/*' ] }`· ;
-   Regex 路径匹配 : `{ include: [ /^\/public\/.*/ ] }`· ;

```ts
import {NgxGoogleAnalyticsModule, provideGoogleAnalytics, provideGoogleAnalyticsRouter} from '@hakimio/ngx-google-analytics';

@NgModule({
    imports: [
        // ...
        NgxGoogleAnalyticsModule // ⬅️ Google Analytics module
    ],
    providers: [
        provideGoogleAnalytics('ga4-tag-id'),
        provideGoogleAnalyticsRouter({ // ⬅️ Google Analytics router provider
            include: ['/some-path'],
            exclude: ['*/another/path/*']
        })
    ]
})
export class AppModule {}
```

## 谷歌分析服务

该服务提供了强烈的打字方式 `gtag()` 命令。 除了类型检查以外,它没有 参数的任何其他验证或转换.

### 注册分析事件

```ts
@Component()
export class TestFormComponent {

    private readonly gaService = inject(GoogleAnalyticsService);

    onUserInputName() {
        this.gaService.event('enter_name', {
            category: 'user_register_form',
            label: 'Name',
            options: {
                customDimension: 'foo_bar'
            }
        });
    }

    onUserInputEmail() {
        this.gaService.event('enter_email', {
            category: 'user_register_form',
            label: 'Email'
        });
    }

    onSubmit() {
        this.gaService.event('submit', {
            category: 'user_register_form',
            label: 'Enviar' 
        });
    }

}
```

### 人工注册页面浏览

```ts
@Component()
export class TestPageComponent implements OnInit {

    private readonly gaService = inject(GoogleAnalyticsService);

    ngOnInit() {
        this.gaService.pageView('/test', {
            title: 'Test the Title'
        });
    }
    
    onUserLogin() {
        this.gaService.pageView('/test', {
            title: 'Test the Title',
            options: {
                user_id: 'my-user-id'
            }
        });
    }

}
```

## 指令

指令提供了一种简单的登记分析事件的方法. 而不是手动使用 `GoogleAnalyticsService`, (中文(简体) ), 您可以简单地添加 `ga*` 属性到您的 html 元素.

### 简单的指令使用

默认情况下,指令调用 `gtag()` ,但您也可以通过提供 `gaBind` 属性.

**关键是:** 记住要导入 `NgxGoogleAnalyticsModule` 在您使用的所有独立组件和模块中 `ga*` 指令。 。 .

```html
<div>
  <button gaEvent="click_test" gaCategory="ga_directive_test">Click Test</button>
  <button gaEvent="focus_test" gaCategory="ga_directive_test" gaBind="focus">Focus Test</button>
  <button gaEvent="blur_test" gaCategory="ga_directive_test" gaBind="blur">Blur Test</button>
  <button gaEvent="custom_test" gaCategory="ga_directive_test" gaBind="customEvent">Custom Event Test</button>
</div>
```

### 使用时间 `input` 要素

何时 `gaEvent` 指令用于形式元素, 默认 `trigger` 实值 `focus` 活动.

```html
<div>
  <input gaEvent="fill_blur" gaCategory="ga_directive_input_test" placeholder="Auto Blur Test"/>
</div>
```

### 指令组

这个 `gaCategory` 可针对更高层次的html元素组指定指令,为所有人指定相同的类别 儿童元素.

```html
<div gaCategory="ga_test_category">
  <button gaEvent gaAction="click_test">Click Test</button>
  <button gaEvent gaAction="focus_test" gaBind="focus">Focus Test</button>
  <button gaEvent gaAction="blur_test" gaBind="blur">Blur Test</button>
</div>
```

## 常见问题

### @hakimio/ngx-google-analytics 是什么？

Angular 应用程序的简单 Google 分析包

### 如何安装 @hakimio/ngx-google-analytics？

在项目目录运行 npm install @hakimio/ngx-google-analytics，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@angular/common（\>=16\.0\.0）、@angular/core（\>=16\.0\.0）、@angular/router（\>=16\.0\.0）、rxjs（^7\.4\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @hakimio/ngx-google-analytics 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @hakimio/ngx-google-analytics 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @hakimio/ngx-google-analytics 可以商用吗？

@hakimio/ngx-google-analytics 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @hakimio/ngx-google-analytics 的下载量有多少？

根据 npm 官方下载统计，@hakimio/ngx-google-analytics 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,260 次，日均约 242 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @hakimio/ngx-google-analytics 还在维护吗？

最新版本 15\.0\.0 发布于 2023/10/03（3 年前）；至今共发布 1 个版本，其中过去 12 个月发布了 0 个；首次发布于 2023/10/03。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

