【问题标题】:How can I use @HostListener('window:beforeunload') to cancel routing?如何使用 @HostListener('window:beforeunload') 取消路由?
【发布时间】:2019-11-27 16:23:24
【问题描述】:

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

我通过click调用确认,在收到false的情况下,路由仍然发生。

也许,我错过了什么?

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
            }
        }
    }
}

【问题讨论】:

  • 你为什么不使用 angular canDeactivate
  • 因为它不仅应该在导航时起作用,而且在单击页面上的任何其他按钮时也应该起作用
  • 当点击按钮是什么行为,你不是在导航到另一个页面吗?
  • 没有。验证发生在组件更改或切换到另一个路由时
  • 但是beforeonload host ;istener 会在点击浏览器返回按钮的时候触发吗?

标签: angular debugging onbeforeunload


【解决方案1】:

如果有人派上用场,就会找到解决方案。

对于卸载前:

@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]

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 1970-01-01
    • 2019-11-09
    • 2022-06-16
    • 2017-07-22
    • 2010-10-25
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多