我需要制作一个简单的确认窗口,我看到了很多如何通过额外操作来完成此操作的示例(例如等待表单文件上传不存在)。但我只需要创建一个带有默认文本的默认确认窗口(如下图所示),以便在用户想要离开当前页面时显示它。我无法完全理解在处理 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?
}
}
}
如果您提供代码示例,那就太好了,但我很感谢任何形式的帮助。
最佳答案
您应该区分 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/