Angular 6 : simple confirmation on page leaving

标签 angular typescript onbeforeunload angular-router-guards

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

image example

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

example.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?
    }
}

example.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?
            }
        }
}

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

最佳答案

您应该区分 window 上的 beforeunload native 事件和 canDeactivate 防护。 当您尝试关闭选项卡/窗口时会触发第一个。这样,当它被触发时,您可以confirm(...)用户并对其执行event.preventDefault()以取消关闭选项卡/窗口。

谈论 CanDeactivate 守卫,它应该返回一个 boolean 的 observable/promise/plain-value ,它会告诉你是否可以停用当前路由。

因此,最好将两种方法分开(一种用于 beforeunload,另一种用于保护)。因为如果您希望将行为更改为不仅使用 native 确认,还使用自定义模式窗口,则 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();
  }
}

另一方面,Guard 希望返回 bool 值(或 Promise, 或可观察)。所以在这里你可以只返回你的条件的结果:

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

因此,在您的 CanDeactivate 防护中,它将像 return component.canDeactivate()

一样使用

关于 Angular 6 : simple confirmation on page leaving,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199903/

相关文章:

Angular 6 - 在 ngFor 内选择

node.js - Angular 5 部署到 Heroku 失败并出现应用程序错误 H10

inheritance - TypeScript:静态属性和继承

AngularJS + typescript : cannot inject $routeProvider

javascript - beforeunload - 自己的消息和功能成功与否?

angular - 路由器存储无法识别路由器参数

Angular (4.x.x) Material CheckBox 组件 (mat-checkbox) : [checked] not working

javascript - 使用注入(inject)服务扩展 Angular Component 方法

javascript - 使用 onbeforeunload 确认时是否可以捕获用户的回答?

storage - 在 beforeunload 上删除 indexeddb 的方法