Search code examples
angularangular-routing

How to know whether the navigation is cancelled or not?


I am navigating to a route but one of the route guard is returning false in Angular 13. how to know whether navigation is done or cancelled. I have done below but then block and finally block consoles are printing even the route guard returns false.

this.router.navigate(['/user/admin/editor'])
      .then(() =>{
        console.log('then block');
        
      })
      .catch(() => {
        console.log('catch block');
        
      })
      .finally(() => {
        console.log('final block');
        
      });

Solution

  • You can subscribe to the router events, more specifically, to the NavigationCancel event:

    this.router.events.pipe(
      filter(e => e instanceof NavigationCancel)
    ).subscribe(() => {
      console.log('navigation was cancelled');
    })