Angular - How do I cancel a Route Change triggered

2019-05-17 08:36发布

In my application I want to show a prompt message box or a modal whenever the user hits back button. I am able to use onPopState event but it doesn't prevent the user from navigating backwards. So far, I have this:

    window.onpopstate = (event) => 
      event.preventDefault();
      this.modal.showModal();
    };

3条回答
疯言疯语
2楼-- · 2019-05-17 09:01

Here's how i do it in my app.

Import angular's 'Location' API in your module.

import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';  

Add it to the provider's list

providers: [ Location, {provide: LocationStrategy, useClass: PathLocationStrategy},  ... ]

Note - you may not need the 'PathLocatioStrategy' part of that if you're not rewriting URLs manually.

Then in your root component, or a singleton service, import Location again...

import { Location } from '@angular/common';

inject it into the constructor

constructor (private location: Location) {  ....

Then subscribe to the 'back' PopStateEvent.

location.subscribe((back: PopStateEvent) => {
    ... your code here ...
     this.modal.showModal();
}); 

If you're using the Angular router or anything else that uses the Angular Location API and path-rewriting, it may prevent this from working. I don't use the Angular router much but I'm guessing it probably has a method for dealing with PopStateEvents.

查看更多
贪生不怕死
3楼-- · 2019-05-17 09:05

Instead of using the window object, you should use a route guard. In your route configuration, you should add a CanDeactivate guard. Follow this guide, it is very similar to what you want to accomplish.

查看更多
beautiful°
4楼-- · 2019-05-17 09:15

Angular 2/4 provides a way to do just the same. And the solution is canDeactivate.

canDeactivate is a route property that can be added to the route whose component contains the back button.

The canDeactivate guard takes a service as an Input. The Service implements the canDeactivate Interface(@angular/router).

{
path: "<some path>", component: BackButtonComponent, canDeactivate:[nameOfService]
}

If only this service returns true, the the user would be allowed to go back.

Further Reading: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

查看更多
登录 后发表回答