NavigationStart何时在Angular 2中触发?

时间:2017-02-28 06:22:40

标签: angular angular2-routing

在从外部站点到此站点的重定向后,是否在页面加载时触发了NavigationStart事件?

从外部站点重定向到SomeComponent时未触发的示例代码。

import { Router, ActivatedRoute, NavigationStart } from '@angular/router'; 

export class SomeComponent { 
   constructor(public _router: Router, private _activeRoute: ActivatedRoute,    private _location: Location) {
     this.router = _router; 
     this.router.events
         .filter(e => e instanceof   NavigationStart)     
         .pairwise()
         .subscribe((e) => { alert(e); }); 
   }
}

2 个答案:

答案 0 :(得分:2)

您无法收到有关导航期间创建和添加的组件内NavigationStart的通知。 而是将代码添加到AppComponent

import { Router, ActivatedRoute, NavigationStart } from '@angular/router'; 

export class AppComponent { 
   constructor(public _router: Router, private _activeRoute: ActivatedRoute,    private _location: Location) {
     this.router = _router; 
     this.router.events
         .filter(e => e instanceof   NavigationStart)     
         .pairwise()
         .subscribe((e) => { alert(e); }); 
   }
}

答案 1 :(得分:0)

我将以下代码用于角度8

export class AppComponent {
  constructor(private router:Router) { 
    this.router.events.subscribe((e) => { if(e instanceof NavigationStart) { console.log(e); } });
  }
}