When is NavigationStart fired in Angular 2?

社会主义新天地 提交于 2019-12-24 08:49:08

问题


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); }); 
   }
}

回答1:


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); }); 
   }
}



回答2:


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); } });
  }
}


来源:https://stackoverflow.com/questions/42501637/when-is-navigationstart-fired-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!