我尝试在卸载组件之前调用确认,但是它不起作用。
我通过点击呼叫确认,并且在我收到错误消息的情况下,仍会进行路由。
可能是我缺少什么吗?
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
}
}
}
}
答案 0 :(得分:0)
如果有人派上用场,就会找到解决方案。
对于beforeunload:
@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]