【问题标题】:Angular 6: simple confirmation on page leavingAngular 6:页面离开时的简单确认
【发布时间】:2019-06-09 12:38:33
【问题描述】:

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

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

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

如果你能提供一个代码示例,那就太好了,但我很感激任何帮助。

【问题讨论】:

    标签: angular typescript onbeforeunload angular-router-guards


    【解决方案1】:

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

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

    因此最好将两种方法分开(一种用于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();
      }
    }
    

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

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

    所以在你的 CanDeactivate 守卫中,它将像 return component.canDeactivate() 一样使用

    【讨论】:

    • 但是如何检测选择了哪个选项(离开按钮或取消按钮)?因为这取决于他是留下还是离开
    • 每个按钮在html中应该有(click)="functionName()"属性,指的是你要调用哪个函数。
    • canLeavePage() 函数给我以下错误 -> 声明类型既不是“void”也不是“any”的函数必须返回一个值。ts(2355)
    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多