我有某种“未保存的更改”弹出窗口,用户可以在其中取消后退导航。在这种情况下,当用户单击“取消”(canDeactivate
后卫返回false),然后尝试向后导航(称为“ canDeactivate
”)时,用户选择“保留而不保存”(canDeactivate
后卫返回true),则导航返回会发生两次。
组件
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
return !this.unsavedChangesAvailable;
}
后卫
canDeactivate(
component: BLAComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!component.canDeactivate()) {
this.unsavedChangesModal = this.dialog.open(UnsavedChangesModalComponent, {
height: 'auto',
width: 'auto'
});
return this.unsavedChangesModal.afterClosed().pipe(
map((choice: boolean) => {
return choice;
}));
} else {
return of(true);
}
}
模式
<button mat-button [mat-dialog-close]="false" cdkFocusInitial>
{{ 'EDITOR.UNSAVED_CHANGES_MODAL.CANCEL' | translate }}</button>
<button mat-button [mat-dialog-close]="true">{{
'EDITOR.UNSAVED_CHANGES_MODAL.LEAVE_WITHOUT_SAVE' | translate }}
</button>
该问题不仅出现在Angular 6中,而且出现在最新版本8中。我已经更新了它,因为我认为问题已解决(https://github.com/angular/angular/issues?utf8=%E2%9C%93&q=is%3Aissue+candeactivate+twice),但是更新没有解决问题。