Angular - 如何取消由“后退"按钮触发的路线更改? [英] Angular - How do I cancel a Route Change triggered from the Back button?
问题描述
在我的应用程序中,我想在用户点击后退按钮时显示提示消息框或模式.我可以使用 onPopState 事件,但它不会阻止用户向后导航.到目前为止,我有这个:
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();
};
推荐答案
Angular 2/4 提供了一种方法来做同样的事情.解决方案是 canDeactivate.
Angular 2/4 provides a way to do just the same. And the solution is canDeactivate.
canDeactivate 是一个路由属性,可以添加到其组件包含后退按钮的路由中.
canDeactivate is a route property that can be added to the route whose component contains the back button.
canDeactivate 守卫将服务作为输入.该服务实现了canDeactivate 接口(@angular/router).
The canDeactivate guard takes a service as an Input. The Service implements the canDeactivate Interface(@angular/router).
{
path: "<some path>", component: BackButtonComponent, canDeactivate:[nameOfService]
}
如果仅此服务返回 true,则允许用户返回.
If only this service returns true, the the user would be allowed to go back.
进一步阅读:https://angular.io/guide/router#candeactivate-handling-unsaved-changes
这篇关于Angular - 如何取消由“后退"按钮触发的路线更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!