Angular 6:页面离开时的简单确认

hof*_*eyn 6 onbeforeunload typescript angular angular-router-guards

我需要制作一个简单的确认窗口,我看到了很多关于如何使用额外操作来完成的示例(例如等到表单的文件上传不是字段)。但是我只需要创建一个带有默认文本的默认确认窗口(如下图所示),以便在用户想要离开当前页面时显示它。而且我无法完全理解我应该在处理before unload事件中证明什么逻辑。

图像示例

如果它重复了一些问题,我最近很抱歉,但是,我没有找到任何解决方案。所以我有:

例子.guard.ts

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | boolean;
}

@Injectable()
export class ExampleGuard implements CanDeactivate<CanComponentDeactivate> {

    constructor() { }

    canDeactivate(component: CanComponentDeactivate): boolean | Observable<boolean> {
        return component.canDeactivate() ?
            true :
            confirm('message'); // <<< does confirm window should appear from here?
    }
}
Run Code Online (Sandbox Code Playgroud)

示例.component.ts

export class ExampleComponent implements CanComponentDeactivate {

    counstructor() { }

    @HostListener('window:beforeunload', ['$event'])
        canDeactivate($event: any): Observable<boolean> | boolean {
            if (!this.canDeactivate($event)) {
                // what should I do here?
            }
        }
}
Run Code Online (Sandbox Code Playgroud)

如果您提供代码示例,那就太好了,但我感谢任何帮助。

Dan*_*udz 6

您应该区分beforeunload本地事件 onwindow和 canDeactivate 守卫。当您尝试关闭选项卡/窗口时触发第一个。因此,当它被触发时,您可以confirm(...)使用并执行event.preventDefault()它以取消关闭选项卡/窗口。

谈到CanDeactivate守卫,它应该返回一个布尔值的可观察/承诺/普通值,它会告诉你是否可以停用当前路线。

所以最好分开两种方法(一种用于beforeunload守卫,第二种用于守卫)。因为如果您想要更改行为,不仅使用本机确认,还使用您的自定义模式窗口,默认事件处理程序在beforeunload处理同步代码时将不起作用。因此,beforeunload您confirm只能用于要求用户不要离开页面。

loading = true;
@HostListener('window:beforeunload', ['$event'])
canLeavePage($event: any): Observable<void> {
  if(this.loading && confirm('You data is loading. Are you sure you want to leave?')) {
    $event.preventDefault();
  }
}
Run Code Online (Sandbox Code Playgroud)

另一方面,Guard 想要返回布尔值(或 Promise 或 Observable)。所以在这里你可以只返回你的条件的结果:

canDeactivate(): boolean {
  return this.loading && confirm('You data is loading. Are you sure you want to leave?');
}

Run Code Online (Sandbox Code Playgroud)

所以在你的CanDeactivate守卫中它会像return component.canDeactivate()