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

时间:2016-08-03 06:35:29

标签: javascript angular angular-routing

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

// 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'.

1 个答案:

答案 0 :(得分:1)

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

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