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
If you’d like to cancel a navigation, you shoud use the
canActivate
guard and returnfalse
of anObservable
returningfalse
or redirect to a page by returning aUrlTree
.you can do it like this with event reason as well
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