关闭mat-dialog后如何将返回值发送到CanDeactivate Guard。 Angular CanDeactivate防护|角材料对话框

时间:2019-01-30 10:22:48

标签: angular angular-material angular-router-guards

我正在使用CanDeactivate Guard找出未保存的更改,如果发生更改,我将在离开页面之前显示确认材料对话框。基于对话框动作,我将返回布尔值。

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);
}

与确认方法相同。我想根据对话框操作返回值浏览页面

1 个答案:

答案 0 :(得分:0)

您非常幸运,因为canDeactivate的可能返回类型之一是Observable<boolean>,而这正是返回dialogRef.afterClosed()的原因。

因此,只需将dialogRef定义为UnsavedChangesComponentreturn component.dialogRef.afterClosed();的属性即可!