Angular 如何在关闭“垫”对话框|角度CanDeactivate Guard |角度材质对话框后将返回值发送到CanDeactivate Guard

Angular 如何在关闭“垫”对话框|角度CanDeactivate Guard |角度材质对话框后将返回值发送到CanDeactivate Guard,angular,angular-material,angular-router-guards,Angular,Angular Material,Angular Router Guards,我正在使用CanDeactivate Guard查找未保存的更改,如果发生更改,我将在离开页面之前显示“确认材料”对话框。基于对话框操作,我将返回布尔值 CanDeactivateGuard.ts: export class DeactivateGuard implements CanDeactivate<UnsavedChangesComponent> { canDeactivate( component: UnsavedChangesComponent, c

我正在使用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;
    }
  }
}
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
      }
    });
  }
<button mat-button color="primary" (click)="save()">Save</button>
<button mat-button color="primary" (click)="cancel()">Cancel</button>
save(){
    this.dialogRef.close(true);
}

cancel() {
    this.dialogRef.close(false);
}
confirmDialog.html:

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;
    }
  }
}
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
      }
    });
  }
<button mat-button color="primary" (click)="save()">Save</button>
<button mat-button color="primary" (click)="cancel()">Cancel</button>
save(){
    this.dialogRef.close(true);
}

cancel() {
    this.dialogRef.close(false);
}

这和确认方法一样。我想根据dialog action返回值来浏览页面,你很幸运,因为
canDeactivate
的一种可能返回类型是
可观察的
,而这正是返回的
dialogRef.afterClosed()

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