Search code examples
angularrxjsrxjs6

Angular combine multiple router events


I just have an query I'm having an two router events snippet

    this.router.events.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
      .subscribe((events: RoutesRecognized[]) => {
        this.previousUrl = events[0].urlAfterRedirects;
        this.currentUrl = events[1].urlAfterRedirects;
});

this.router.events
.pipe(filter(e => e instanceof NavigationStart))
.subscribe((e: NavigationStart) => {
  const navigation = this.router.getCurrentNavigation();
});

Though these are working fine individually,

In order to optimize, can I merge/combine this router events and use only one?.


Solution

  • Of course we can. Why do we need to listen to the same event emitter twice? You can do something like this:

        this.router.events.pipe(pairwise())
      .subscribe((events: any) => {
        if (events[0] instanceof NavigationStart) {
          const navigation = this.router.getCurrentNavigation();
        } else if (events[1] instanceof RoutesRecognized) {
          this.previousUrl = events[0].urlAfterRedirects;
          this.currentUrl = events[1].urlAfterRedirects;
        }
      });
    

    Instead of filtering events up top, you listen to everything and apply your logic based on the event type.