我尝试在组件卸载之前调用确认,但它不起作用。
我通过点击调用确认,在收到错误的情况下,路由仍然会发生。
也许,我错过了什么?
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]
不幸的是,这篇文章在离开组件时有效;但是,当单击浏览器中的“刷新”按钮时,它不起作用。