When is NavigationStart fired in Angular 2?

2019-08-02 09:10发布

Is NavigationStart event fired on page load, after redirection has occurred from an external site to this site?

Sample code which is not fired on redirection from external site to 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条回答
我命由我不由天
2楼-- · 2019-08-02 09:35

You can't get notified about NavigationStart inside the component that is created and added during navigation. Instead add the code to 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); }); 
   }
}
查看更多
甜甜的少女心
3楼-- · 2019-08-02 09:37

I used the code below for angular 8

export class AppComponent {
  constructor(private router:Router) { 
    this.router.events.subscribe((e) => { if(e instanceof NavigationStart) { console.log(e); } });
  }
}
查看更多
登录 后发表回答