Search code examples
angularangular2-routing

angular 2 router.events subscription not firing


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!


Solution

  • 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.