错误 TS2304:找不到名称“ga”

r3p*_*ica 3 google-analytics angular

我正在使用 Angular4 并尝试安装分析。我遵循了本指南:

https://blog.thecodecampus.de/angular-2-include-google-analytics-event-tracking/

但是当我尝试构建我的项目时,出现错误:

错误 TS2304:找不到名称“ga”。

我已经检查了我的 package.json 并且我已经"@types/google.analytics": "0.0.38",安装在我的devDependencies 中。当我开始打字时,我可以看到智能感知知道它是一种UniversalAnalytics.ga类型,但我无法让它工作。

我尝试将代码更改为:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    let ga: Function;
    ga('set', 'page', event.urlAfterRedirects);
    ga('send', 'pageview');
  }
});
Run Code Online (Sandbox Code Playgroud)

它可以编译,但在 console.log 中我收到一条错误消息:

Uncaught (in promise): TypeError: ga is not a function

如果我改成这样:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    let ga: any;
    ga('set', 'page', event.urlAfterRedirects);
    ga('send', 'pageview');
  }
});
Run Code Online (Sandbox Code Playgroud)

我犯了同样的错误。有谁知道为什么?

这是完整的代码:

import { Component, OnInit, AfterViewChecked, AfterViewInit } from "@angular/core";
import { ActivatedRoute, Params, Router, NavigationEnd } from "@angular/router";

import { ResultsService } from "./shared/results.service";
import { HeightService } from "./shared/height.service";

@Component({
  selector: 'bzRoot',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewChecked, AfterViewInit {
  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resultsService: ResultsService,
    private _heightService: HeightService,
    public router: Router) {
  }

  ngOnInit() {
    this._activatedRoute.queryParams.subscribe((params: Params) => {
      // Only update the elq if it changes (remember: changing a parameter causes the page to refresh)
      var elq = params['elqid'];
      if (elq) {
        this._resultsService.elq = elq;
      }
    });
  }

  ngAfterViewChecked() {
    this._heightService.resize();
  }

  ngAfterViewInit() {
    //this.router.events.subscribe(event => {
    //  if (event instanceof NavigationEnd) {
    //    let ga: Function;
    //    ga('set', 'page', event.urlAfterRedirects);
    //    ga('send', 'pageview');
    //  }
    //});
  }
}
Run Code Online (Sandbox Code Playgroud)

Can*_*Can 8

不知何故@types/google.analytics 包接缝被打破。只需将此添加到您的代码中:

declare let ga: Function;
Run Code Online (Sandbox Code Playgroud)

我会更新我的博客文章。


Arn*_*rdt 7

您可以添加google.analytics到 tsconfig.json 中的类型

"types": [
  "node",
  "google.analytics",
],
Run Code Online (Sandbox Code Playgroud)

..或者你可以types从配置中删除整个属性,让它在@types 中全部使用。在此处检查“类型”部分:https : //www.typescriptlang.org/docs/handbook/tsconfig-json.html


r3p*_*ica 5

我找到了一种替代声明的方法。我将代码修改为:

this._router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    (<any>window).ga('set', 'page', event.urlAfterRedirects);
    (<any>window).ga('send', 'pageview');
  }
});
Run Code Online (Sandbox Code Playgroud)

它奏效了。我在另一个指令中找到了这个方法。