Angular 2 router.events subscription not getting burned
I am using a breadcrumbs component that subscribes to router.events. The problem is that the first time the component is loaded, it doesn't start 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 clicking on the link with the routerLink property, the subscription returns values ββand works fine. I compared my project with a working one with Augury and a breadcrumb component, the Router state looks like this: Router not working
And working: Working router
Let me now if you need more information to help :) Thanks in advance!
source to share
Your code downloads data asynchronously via subscription. I suggested putting it in the constructor () so it will execute before the lifecycle is bound this way before OnInit () and the data will be loaded before you click on the link. It was correct. So you better take a look at Observables for a better understanding of what's going on.
source to share