I want to detect a route from the current component and tried something like that. But it is triggered on every route starts and ends. Instead of this, how can I detect only the route changes when routes from this DetailsComponent
?
export class DetailsComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
}
if (event instanceof NavigationEnd) {
}
});
}
}
I need to get the url while navigation from this DetailsComponent
and make an operation if the url is not /employees
.
The reason your events continue to be detected, is because you are not unsubscribing from router.events
when your DetailsComponent
is destroyed.
If you simply unsubscribe, it should work for you:
export class DetailsComponent {
private sub = this.router.events
.pipe(
filter(event => event instanceof NavigationStart),
map(event => event as NavigationStart), // appease typescript
filter(event => event.url !== '/employees')
)
.subscribe(
event => console.log('[DetailsComponent] NOT going to "/employees"!', event)
);
constructor(private router: Router) { }
ngOnDestroy() {
console.log('>> STOP listening to events for DetailsComponent');
this.sub.unsubscribe();
}
}
Here's a StackBlitz example.
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