angular 2 router.events subscription not firing

Viewed 12537

I'm using a breadcrumbs component which make a subscription to router.events. The problem is the first time the component is loaded, it does not fire the subscription.

ngOnInit(): void {
  console.log("oninit beradcumbs");
  this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
    this.breadcrumbs = [];
    let currentRoute = this.route.root,
    url = '';
    do {
      const childrenRoutes = currentRoute.children;
      currentRoute = null;
      childrenRoutes.forEach(route => {
        if (route.outlet === 'primary') {
          const routeSnapshot = route.snapshot;
          url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
          this.breadcrumbs.push({
            label: route.snapshot.data,
            url:   url
          });
          currentRoute = route;
        }
      });
    } while (currentRoute);
    console.log("Breadcumbs",this.breadcrumbs);
  });
}

When a link with routerLink property is clicked, the subscription emits the values and it works fine. I compared my project with a working one with Augury and in the breadcrumb component, the state of Router looks like this: Not working Router

And the working one: Working router

Let me now if you need more info to help :) Thanks in advance!

2 Answers

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.

Related