Hendry Hendry - 17 days ago 7
Javascript Question

How to cancel route change in Angular 2?

I would like to cancel the route change when the user click back or forward button in the browser.
So far I manage to capture the route change event as in the code below:

constructor(router:Router) {
router.events
.subscribe((event:Event) => {
// some logic.
// event.preventDefault(); ?
});
}


I couldn't find any method / member in event to stop the event default. Then I will get this error on console because I have no route config registered as intended, this is because I use
location.go()
to modify the url.

Error: Uncaught (in promise): Error: Cannot match any routes: 'Some/Url'


Is there any way to cancel the route change so Angular doesn't look at the route config?

Answer

You may use canDeactivate guard when defining route, this will help you writing logic when changing route.

You may simply return true or false, based upon if you want to continue or reject route navigation, you also get reference to your component instance which is active for that route so as to read any property on it.

Signature of the method is like below,

canDeactivate(component: T,
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot) :  
     Observable<boolean>|Promise<boolean>|boolean

You may read more about it [here][1]./api/router/index/CanDeactivate-interface.html