在我的应用程序中,我想在用户点击后退按钮时显示提示消息框或模式。我可以使用 onPopState 事件,但它不会阻止用户向后导航。到目前为止,我有这个:
window.onpopstate = (event) =>
event.preventDefault();
this.modal.showModal();
};
最佳答案
这是我在我的应用程序中的做法。
在您的模块中导入 Angular 的“位置”API。
import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
将其添加到提供者的列表中
providers: [ Location, {provide: LocationStrategy, useClass: PathLocationStrategy}, ... ]
注意 - 如果您不手动重写 URL,您可能不需要其中的“PathLocatioStrategy”部分。
然后在您的根组件或单例服务中,再次导入 Location...
import { Location } from '@angular/common';
将其注入(inject)到构造函数中
constructor (private location: Location) { ....
然后订阅“返回”PopStateEvent。
location.subscribe((back: PopStateEvent) => {
... your code here ...
this.modal.showModal();
});
如果您正在使用 Angular 路由器或任何其他使用 Angular Location API 和路径重写的东西,它可能会阻止它工作。我不常使用 Angular 路由器,但我猜它可能有处理 PopStateEvents 的方法。
关于javascript - Angular - 如何取消从后退按钮触发的路由更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45865929/