如何让 Angular canDeactivate Service 等待模态对话框响应?

How to make Angular canDeactivate Service wait for Modal Dialog response?

我在组件内部有一个函数来检查我是否可以通过评估表单状态离开路线。 如果状态与我需要离开路线的条件相匹配,它会显示一个对话框以确认或取消。 我在我的 canDeactivate 服务中调用了这个函数,但它在等待对话确认之前触发了响应。

我已经用组件的功能在 canDeactivate 服务中放置了一个 console.log。 当不需要确认时,它会按预期显示 true。但另一方面,当需要确认时,在对话框出现之前显示undefined。

canDeactivateService.ts

@Injectable()
export class ProdutosDeactivateGuard implements CanDeactivate<ExampleComponent> {

  canDeactivate(
      component: ExampleComponent,
      route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ): boolean {
      return component.checkStatus();
  }
}

示例-component.ts

checkStatus() {
    if (!this.form.pristine && this.form.touched) {
      const dialogRef = this.dialog.open(DeactivateDialogComponent);
      dialogRef.afterClosed().subscribe(result => {
        if (result === 'true') {
          return true;
        } else {
          return false;
        }
      });
    } else {
      return true;
    }
  }
}

我希望服务等待确认。我该怎么做?

您是否尝试过返回一个可观察对象?正如我在您的代码中看到的 afterClosed() returns one.

例如:

@Injectable() 导出 class ProdutosDeactivateGuard 实现 CanDeactivate {

canDeactivate(
      component: ExampleComponent,
      route: ActivatedRouteSnapshot,
      state: RouterStateSnapshot
    ): Observable<boolean> {
      return component.checkStatus();
  }
}

checkStatus() {
    if (!this.form.pristine && this.form.touched) {
      const dialogRef = this.dialog.open(DeactivateDialogComponent);
      return dialogRef.afterClosed().pipe(map(result => {
        return result === 'true';
      }));
    } else {
      return of(true);
    }
  }
}