Home > Back-end >  Angular router events subscribe event type "any"
Angular router events subscribe event type "any"

Time:05-19

I am using the following code to find out the URL at the NavigationEnd event of the router.

        this.router.events
            .pipe(filter((e) => e instanceof NavigationEnd))
            .subscribe((ev: any) => {
                let url = ev.url;})

I don't want to use "any" in the code. What should I replace it with? I tried "NavigationEnd" and "Event" instead of "Any". In both cases, I got the "No overload matches this call." error.

CodePudding user response:

You need to use Event from @angular/router i think.. you can import it

CodePudding user response:

Try this

router.events.pipe(filter(e => e instanceof NavigationEnd))
.subscribe((e: NavigationEnd) => {
        let url = e.url;       
 });

CodePudding user response:

RouterEvent must be what you need.

  this.router.events
    .pipe(filter((e) => e instanceof NavigationEnd))
    .subscribe((ev: RouterEvent) => {
      console.log(ev.url);
  });

CodePudding user response:

Try passing a RxJS observer object to the subscribe() function instead of individual callback.

import { NavigationEnd, RouterEvent } from '@angular/router';

this.router.events.pipe(
  filter((e: RouterEvent) => e instanceof NavigationEnd)
).subscribe({
  next: (e: NavigationEnd) => {
    let url = ev.url;
  }
});

CodePudding user response:

You can use a type predicate on the filter fn to help Typescript decipher what's the filter intention like this.

this.router.events
  .pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
  .subscribe((ev: NavigationEnd) => {
    let url = ev.url;
  });

Cheers

  • Related