angular - 错误 TS2304 : Cannot find name 'ga'

标签 angular google-analytics

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

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

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

error TS2304: Cannot find name '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');
  }
});

它可以编译,但在 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');
  }
});

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

这是完整的代码:
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');
    //  }
    //});
  }
}

最佳答案

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

declare let ga: Function;

我会更新我的博客文章。

关于angular - 错误 TS2304 : Cannot find name 'ga' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49068350/

相关文章:

Angular 2 Multi-Tenancy 系统 - 用户名为 "subdomain"

javascript - 根据环境有条件地在 Angular 中加载一组不同的工厂

typescript - 如何在 Angular 2 中使用 webrtc?

javascript - 创建二维 View

javascript - Angular:Getter/Setter - Getter 返回未定义

google-analytics - 使用gtag.js发送自定义尺寸

google-analytics - 如何在 Google Analytics(分析)的 Google Tag Manager 中测试和实现数据层

ruby - Universal Analytics 测量协议(protocol) 200 - 没有显示任何内容

javascript - 如何在新的 Google Analytics 代码中放置自定义变量

javascript - "Multiple Google Analytics tags detected"