我尝试在组件卸载之前调用确认,但它不起作用。
我通过点击调用确认,并且在收到错误消息的情况下,路由仍然会发生。
也许我错过了什么?
import { Component, OnInit, OnDestroy, HostListener } from '@angular/core';
Component({
templateUrl: 'some-component.html',
styleUrls: ['./some-component.scss']
})
export class SomeComponent implements OnInit, OnDestroy {
public ifAllowed: boolean = false
@HostListener('window:beforeunload')
onBeforeUnload(event) {
this.checkValue()
}
ngOnDestroy() {
this.checkValue()
}
checkValue() {
if(!ifAllowed) {
let isContinue = confirm('Any unsaved data will be lost. Сontinue?')
if (!isContinue) {
return false // not working
}
}
}
}
最佳答案
如果有人派上用场,就会找到解决方案。
对于卸载前:
@HostListener('window:beforeunload', ['$event'])
onbeforeunload(event) {
if (!ifAllowed) {
event.preventDefault();
event.returnValue = false;
}
}
检查组件更改时: 创建一个守卫
import {Injectable} from '@angular/core';
import {CanDeactivate} from '@angular/router';
@Injectable()
export class ConfirmationGuard implements CanDeactivate<any> {
constructor() {}
canDeactivate(component: any): boolean {
if (component.ifAllowed) {
return confirm('Are you sure?');
}
return true;
}
}
不要忘记在提供者中注册守卫:
providers: [
ConfirmationGuard
]
并在路由模块中为必要的路径添加 canDeactivate 方法:
canDeactivate: [ConfirmationGuard]
关于angular - 如何使用 @HostListener ('window:beforeunload' ) 取消路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59074497/