I'm seeing one subscription to router.events
yield three calls per route change to the callback function, and each reports instanceof event
as ActivationEnd
.
console.log('This code runs only once, at site initialization.');
router.events.subscribe((event: RouterEvent) => {
if (event instanceof ActivationEnd) {
console.log('This should only log once per route change, but logs three times.');
};
});
I found this thread on Github, which seems related, but I'm having a hard time believing this is still an issue...
I'm using Angular 5 (5.2.10).
UPDATE: It appears that this event is getting fired once for each route segment... Checking documentation.
It appears that I should be using NavigationEnd instead of ActivationEnd to achieve the desired result. I should have known that. I think my eyes failed to notice the difference.
Check whether it is initiating multiple times?
if execute twice or multiple times this event,
router.events.subscribe((event: RouterEvent) => {
then this will get fired multiple times.
if (event instanceof ActivationEnd) {
console.log('This should only log once per route change, but logs three times.');
};
So please make it
if (!alreadyexist){
router.events.subscribe((event: RouterEvent) => {
if (event instanceof ActivationEnd) {
console.log('This should only log once per route change, but logs three times.');
};
});
}
You can use distinctUntilChanged
to solve this. Only triggered if URLs are not the same.
let prevUrl = ''
this.router.events.pipe(
filter((e) => e instanceof ActivationEnd),
distinctUntilChanged((prev, curr) => this.router.url === prevUrl),
tap(()=>prevUrl = this.router.url),
).subscribe((event: RouterEvent) => {
console.log('This should only log once per route change, if url is the same ');
});
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