【问题标题】:How to make Angular canDeactivate Service wait for Modal Dialog response?如何让 Angular canDeactivate Service 等待模态对话框响应?
【发布时间】:2019-10-16 14:45:07
【问题描述】:

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

我已经在 canDeactivate 服务中添加了一个console.log 和组件的功能。 当不需要确认时,它按预期显示为真。但另一方面,当需要确认时,它会在对话框出现之前显示未定义。

canDeactivateService.ts

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

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

example-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;
    }
  }
}

我希望服务等待确认。我怎么能这样做?

【问题讨论】:

  • component.checkStatus() 是否在守卫内正确返回值?
  • @Arcteezy 这是问题所在。当不需要对话框时,它会正确返回。但是当需要对话框时,守卫在等待函数响应之前触发返回。

标签: angular asynchronous angular-material modal-dialog candeactivate


【解决方案1】:

你试过返回一个 observable 吗?正如我在您的代码中看到的那样,afterClosed() 返回一个。

例如:

@Injectable() 导出类 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);
    }
  }
}

【讨论】:

  • 感谢您的支持!现在工作正常!我会看一些关于 Observable 的资料。我之前也尝试过使用它,但我仍然不太了解它。
猜你喜欢
  • 2020-04-16
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多