我实现了以下方法,用于在离开表单之前警告访问者:
pending-changes.guard.ts:
import { CanDeactivate } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
// if there are no pending changes, just allow deactivation; else confirm first
return component.canDeactivate() ?
true :
// NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
// when navigating away from your angular app, the browser will show a generic warning message
// see http://stackoverflow.com/a/42207299/7307355
confirm('WARNING: You will have to re-choose any images if you go back. Press Cancel to stay on the page, or OK to lose these changes.');
}
}
在我的组件类中:
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return false;
// insert logic to check if there are pending changes here;
// returning true will navigate without confirmation
// returning false will show a confirm dialog before navigating away
}
我正在使用的组件中有一个导航条件:
this.router.navigate(['/thank-you', 'ads', res.data.slug]);
我如何让我的应用导航到“ /谢谢”,而不会导致“警告”,因为此时已提交表单。
谢谢
答案 0 :(得分:1)
您只需在canDeactive
hostListener中插入逻辑即可检查是否正在提交表单。
如果您有提交表单的按钮,只需在单击私有字段formBeingSubmitted
时将其设置为true,然后在逻辑中进行检查即可。
private formBeingSubmitted = false;
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
if(this.formBeingSubmitted){
return true
}
return false;
// insert logic to check if there are pending changes here;
// returning true will navigate without confirmation
// returning false will show a confirm dialog before navigating away
}
public onSubmit(){
this.formBeingSubmitted = true;
}