Angular 2+谷歌分析+路由器导航

Angular 2 + google analytics + router navigation

本文关键字:路由器 导航 谷歌 Angular      更新时间:2023-09-26

我正试图将谷歌分析添加到我的项目中,但遇到了一些导航错误,我正在使用新的路由器,下面是我的代码:

// app.component.ts
declare var ga:Function;
export class App {
    private currentRoute:string;
    constructor(_router: Router, _location: Location) {
        _router.events.subscribe((event:Event) => {
            if(event instanceof NavigationStart) {
                var newRoute = this._location.path() || '/';
                if(newRoute !== this.currentRoute) {
                    ga('send', 'pageview', newRoute);
                    this.currentRoute = newRoute;
                }
            }
        });
    }
}

这就是我得到的错误:

ERROR in [default] angular/src/app/app.ts:18:27
Argument of type '(event: Event) => void' is not assignable to parameter of type 'NextObserver<NavigationStart | NavigationEnd | NavigationCancel | NavigationError> | ErrorObserve...'.
  Type '(event: Event) => void' is not assignable to type '(value: NavigationStart | NavigationEnd | NavigationCancel | NavigationError) => void'.
    Types of parameters 'event' and 'value' are incompatible.
      Type 'NavigationStart | NavigationEnd | NavigationCancel | NavigationError' is not assignable to type 'Event'.
        Type 'NavigationStart' is not assignable to type 'Event'.
          Property 'bubbles' is missing in type 'NavigationStart'.
ERROR in [default] angular/src/app/app.ts:19:23
Cannot find name 'NavigationStart'.
ERROR in [default] angular/src/app/app.ts:20:24
Property '_location' does not exist on type 'App'.

请添加导入语句,看看这是否解决了您的问题:

import {Location} from '@angular/common';
import {NavigationStart} from '@angular/router';