【问题标题】:Angular - Avoid nested subscribe call...which better solution?Angular - 避免嵌套订阅调用......哪个更好的解决方案?
【发布时间】:2021-04-27 22:10:03
【问题描述】:

我有一个扩展 ngOninit 功能的仪表板组件。我需要在组件加载之前验证一些事情。

this.startupSubscription = this.accountService.getInfo().pipe(
  switchMap(account => {
    this.account = account;
    return this.sidebarService.getCompanies(this.account.id.toString());
  }))
  .subscribe(res => {
    if (this.account.isAdmin && Object.keys(res).length === 0) {
      this.router.navigateByUrl('/startup');

    }
    else {
      this.selectedCompany.subscribe(
        res => {
          this.idCompany = res.id;
          this.getDashboardCard(this.account!.id.toString(), this.idCompany.toString());
        }
      );
    }
  }
);

我这里需要的是首先调用account服务,account ID是调用getCompanies服务所必需的,然后我需要检查account是否是Admin(布尔值)以及他是否在我的对象中有一些公司从 getCompanies 服务收到。

如果我是管理员并且没有公司,我必须重定向到启动

否则我调用 ngrx 选择器,我使用 idCompany 并将其用于在仪表板中加载元素。

我认为我写的不是很好,但它确实有效......我还需要回答这种逻辑是否必须在 ngOnInit 中。

【问题讨论】:

标签: angular


【解决方案1】:

只是缺少iif operator

代替第一个.subscribe,继续管道并添加:

iif(
  () => this.account.isAdmin && Object.keys(res).length === 0,
  from(this.router.navigateByUrl('/startup')),
  this.selectedCompany.pipe(
     switchMap((res) => {
        this.idCompany = res.id;
        return this.getDashboardCard(this.account!.id.toString(), this.idCompany.toString())
     }
  ),
)

.subscribe() 仅在管道末端出现一次。

【讨论】:

    猜你喜欢
    • 2022-08-25
    • 2023-01-30
    • 1970-01-01
    • 2020-08-18
    • 2018-11-27
    • 2020-11-30
    • 2020-05-31
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多