skip to Main Content

Is it possible to cancel the route navigation inside the events function?

 this.router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          if (cancel) event.preventDefault(); // <-- ? or something similar
        }
 });

2

Answers


  1. If you’d like to cancel a navigation, you shoud use the canActivate guard and return false of an Observable returning false or redirect to a page by returning a UrlTree.

    Login or Signup to reply.
  2. you can do it like this with event reason as well

    this.router.events.subscribe((event) => {
      if (event instanceof NavigationStart) {
        if (cancel) {
          event.cancel = true;
          event.reason = "navigation canceled";
        }
      }
    });
    

    note: these 2 properties only available in navigationStart event, once started you can not cancel

    also important to unsubscribe from the router events afterwards

    you can check more here: https://angular.io/api/router/NavigationStart

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search