I am trying to trigger action on any NavigationEnd
router event, except when navigating between
a) child routes;
b) on one another specific route.
Here is a piece of my app.routing.ts
:
// some other routes setup...
{ path: 'scrapers/:version', component: SingleScraperComponent, children: [
{ path: '', redirectTo: 'statistics', pathMatch: 'full' },
{ path: 'statistics', component: ScraperStatisticComponent },
{ path: 'targets', component: ScraperTargetsComponent },
]},
// some other routes setup...
Here is my Router
events subscription in SingleScraperComponent
:
// some component code
ngOnInit(): void {
this._router.events.filter(event => event instanceof NavigationEnd).takeWhile(() => this.isAlive).subscribe(
(event: NavigationEnd) => {
console.log(event);
if (event.url.indexOf('site-preview') === -1) {
this._site.resetQuery();
}
}
);
}
// some component code
I could also use OnDestroy
, but I need to know next route after SingleScraperComponent
destruction.
Steps to get current route URL in Angular. Import Router,NavigationEnd from '@angular/router' and inject in the constructor. Subscribe to the NavigationEnd event of the router. Get the current route url by accessing NavigationEnd's url property.
ngOnDestroy doesn't get called because some components do not get destroyed when navigating to a different route.
OnDestroylinkA lifecycle hook that is called when a directive, pipe, or service is destroyed. Use for any custom cleanup that needs to occur when the instance is destroyed.
NavigationEndlinkAn event triggered when a navigation ends successfully.
Ok, I have used routerState
snapshot to verify next route:
ngOnDestroy(): void {
if (this._router.routerState.snapshot.url.indexOf('site-preview') > -1) {
console.log('Hello, from needed route!');
}
}
But if there is a more clear way I would appreciate to know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With