EN VI

Angular combine multiple router events?

2024-03-14 22:30:05
How to 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 instanceof NavigationStart) {
      const navigation = this.router.getCurrentNavigation();
    } else if (events 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.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login