Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ ActivationEnd event callback called multiple times

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.

like image 206
BBaysinger Avatar asked Jun 12 '18 03:06

BBaysinger


3 Answers

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.

like image 191
BBaysinger Avatar answered Nov 15 '22 08:11

BBaysinger


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.');

      };
  });

}
like image 3
Raviteja V Avatar answered Nov 15 '22 08:11

Raviteja V


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 ');    
});
like image 1
xianshenglu Avatar answered Nov 15 '22 09:11

xianshenglu