Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: changing single route emits multiple 'NavigationEnd' events

I am using Angular 4, and this is my code in one of the component where I need to catch that route has changed and reload the page.

ngOnInit() {
        this.router.events.subscribe((value) => {
          if (value instanceof NavigationEnd) {
             console.log(value);
          }
        });
    }

My problem is that I get multiple 'NavigationEnd' events for one route. For some route console.log write even 6,7 values.

How that can happen ?

like image 634
Milos Avatar asked Oct 09 '17 20:10

Milos


1 Answers

I assume that by "reload page" you mean calling the navigate method of this.router. If thats the case, this is most likely related to the fact that you create a new observer of the router events every time that you create an instance of this component, but dont dispose the generated subscription in the ngOnDestroy cycle. To solve this, you could do the following:

import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';    

export class FooComponent implements OnInit, OnDestroy {
   private _routerSub = Subscription.EMPTY;
   constructor(private router: Router){}

   ngOnInit(){
     this._routerSub = this.router.events
         .filter(event => event instanceof NavigationEnd)
         .do(event => console.log(value)) // use do operator for log operations
         .subscribe((value) => {
          //do something with the value
         });
   }

   ngOnDestroy(){
     this._routerSub.unsubscribe();
   }
}
like image 144
Jota.Toledo Avatar answered Oct 23 '22 12:10

Jota.Toledo