angular 2 router.events subscription not firing
Your code is loading data asynchronously via subscribe. I suggested to put it in constructor(), so it will be executed before the lifecycle hook thus before OnInit(), and data will be loaded before you click on the link. Which was right. So look to Observables more closely to understand better what is going on.
Not firing router subscription events after lifecycle hook is there in Angular 9 as well. According to a contributor this, there is no guarantee for the sequence of router events interleaving with the component lifecycle hooks.
We can do a simple test to identify when the router events fire.
constructor(private router: Router) {
console.log('constructor')
this.router.events.pipe(filter(event =>
event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
console.log(event);
});
}
ngOnInit(): void {
console.log('ngOnInit')
}
You will see on the console that router event is printed on the console before the 'ngOnInit' gets printed. So the right place to subscribe to the router events is the constructor.