我正在使用 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/