角度-如何取消从“后退"按钮触发的路线更改? [英] Angular - How do I cancel a Route Change triggered from the Back button?

查看:64
本文介绍了角度-如何取消从“后退"按钮触发的路线更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,无论何时用户单击后退"按钮,我都希望显示一个提示消息框或模式对话框.我可以使用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#可以取消处理未保存的更改

这篇关于角度-如何取消从“后退"按钮触发的路线更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆