1

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

确认对话框.html:

<button mat-button color="primary" (click)="save()">Save</button>
<button mat-button color="primary" (click)="cancel()">Cancel</button>

确认对话.ts:

save(){
    this.dialogRef.close(true);
}

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

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

4

1 回答 1

1

你很幸运,因为 is 的一种可能的返回类型,canDeactivateObservable<boolean>这正是返回的dialogRef.afterClosed()

因此,只需将其定义dialogRef为您保护的UnsavedChangesComponent财产return component.dialogRef.afterClosed();

于 2019-01-30T16:04:22.263 回答