问题
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