Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
356 views
Welcome To Ask or Share your Answers For Others

1 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...