问题
I'm using CanDeactivate Guard for find out the unsaved changes and If changes occurred I am showing the confirm material dialog, before leaving the page. Based on the dialog action I will return the Boolean value.
CanDeactivateGuard.ts:
export class DeactivateGuard implements CanDeactivate<UnsavedChangesComponent> {
canDeactivate(
component: UnsavedChangesComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
if (component.isDirty) {
return component.confirmDialog();
}
else {
return true;
}
}
}
UnsavedChangesComponent.ts:
confirmDialog(): boolean {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '450px',
});
return dialogRef.afterClosed().subscribe(result => {
if (result == true) {
this.save();
return false
}
if (result == false) {
return true
}
});
}
confirmDialog.html:
<button mat-button color="primary" (click)="save()">Save</button>
<button mat-button color="primary" (click)="cancel()">Cancel</button>
confirmDialog.ts:
save(){
this.dialogRef.close(true);
}
cancel() {
this.dialogRef.close(false);
}
It same like confirm method. I want navigate the page based on dialog action return value
回答1:
You are very lucky because one of the possible return types of canDeactivate
is Observable<boolean>
and that's precisely what returns dialogRef.afterClosed()
.
So just define dialogRef
as a property from UnsavedChangesComponent
and return component.dialogRef.afterClosed();
in your guard!
来源:https://stackoverflow.com/questions/54438284/how-to-send-return-value-to-candeactivate-guard-after-close-the-mat-dialog-ang