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

How can I use @HostListener('window:beforeunload') to cancel routing?

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

我是点击调用确认,在收到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
            }
        }
    }
}

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

卸载前:

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