Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...