本文介绍了关闭 mat-dialog 后如何将返回值发送到 CanDeactivate Guard |Angular CanDeactivate Guard |角度材质对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

你很幸运,因为 canDeactivate 的可能返回类型之一是 Observable 和这正是返回 dialogRef.afterClosed() 的原因.

You are very lucky because one of the possible return types of canDeactivate is Observable<boolean> and that's precisely what returns dialogRef.afterClosed().

因此,只需将 dialogRef 定义为 UnsavedChangesComponent 的属性,然后 return component.dialogRef.afterClosed(); 在你的守卫中!

So just define dialogRef as a property from UnsavedChangesComponent and return component.dialogRef.afterClosed(); in your guard!

这篇关于关闭 mat-dialog 后如何将返回值发送到 CanDeactivate Guard |Angular CanDeactivate Guard |角度材质对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 18:48