angular - 如何使用 @HostListener ('window:beforeunload' ) 取消路由?

标签 angular debugging onbeforeunload

我尝试在组件卸载之前调用确认,但它不起作用。

我通过点击调用确认,并且在收到错误消息的情况下,路由仍然会发生。

也许我错过了什么?

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/

相关文章:

javascript - 将时刻格式化为字符串

angular - 清除过滤器 Angular 6

javascript - 多个 onbeforeunload() 和 onunload() 事件

javascript - 检查 onbeforeunload 中的 ace 编辑器以查看是否进行了更改

node.js - 在 Angular 应用程序中,我不断收到此错误 Cannot find module 'fs'

angular - 在 Angular e2e( Protractor )测试期间记录浏览器错误和网络流量

c# - Visual Studio 2008 是否能够对 C# 进行条件编译?

java - 这是阴影变量的情况吗?

r - 如何安装包以便我可以使用调试器单步调试它的 R 代码?

jquery - 使用 "unload"事件自动保存并在注销时调用 ajax : order of actions is causing an issue