would like to subscribe to NavigationEnd events in Angular 14, while using filter from rxjs.

The part of subscribe((event: NavigationEnd) ... causes the following issue

TS2769: No overload matches this call.   Overload 1 of 5, ‘(observer?: NextObserver | ErrorObserver | CompletionObserver | undefined): Subscription’, gave the following error.     Argument of type ‘(event: NavigationEnd) => void’ is not assignable to parameter of type ‘NextObserver | ErrorObserver | CompletionObserver | undefined’.   

…..

See constructor code below with mentioned code snippet:

export class NavigationService implements OnDestroy {

  constructor(private router: Router) {
   this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event: NavigationEnd) => {
         //some logics here
      });
  }
}

Solutions:

The function passed to filter is not a type guard but you can indicate the type like this:

constructor(private router: Router) {
  this.router.events
    .pipe(
      filter((event): event is NavigationEnd => event instanceof NavigationEnd)
    )
    .subscribe(event => {
       // "event" here is now of type "NavigationEnd"
    });
}

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *