How to send return value to CanDeactivate Guard after close the mat-dialog | Angular CanDeactivate Guard | Angular Material Dialog

可紊 提交于 2020-03-03 11:45:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!