【问题标题】:How to send return value to CanDeactivate Guard after close the mat-dialog | Angular CanDeactivate Guard | Angular Material Dialog关闭垫子对话框后如何将返回值发送给 CanDeactivate Guard | Angular CanDeactivate Guard |角度材料对话框
【发布时间】:2019-01-30 10:22:47
【问题描述】:

我正在使用 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);
}

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

【问题讨论】:

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


    【解决方案1】:

    您非常幸运,因为canDeactivate 的一种可能返回类型是Observable&lt;boolean&gt;,而这正是dialogRef.afterClosed() 返回的类型。

    所以只需将dialogRef 定义为UnsavedChangesComponentreturn component.dialogRef.afterClosed(); 中的属性!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-01
      • 2020-02-23
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多