【问题标题】:How to use rxjs for multiple inner nested subscribes如何使用 rxjs 进行多个内部嵌套订阅
【发布时间】:2021-03-05 19:43:12
【问题描述】:

在下面的代码中,我在订阅中使用了订阅。此代码有效,但代码结构非常糟糕。我想使用 rxjs(forkjoin 或 mergemap)重构此代码。我不知道如何实现这一点。有人可以帮我弄这个吗?任何帮助表示赞赏。

this.chapservice.cycle().subscribe((current) => {
      this.selectedCycleId = current.ratingCycleId;
      this.chapService
        .getChapterEvalWithSkills(
          this.activeUser.ipn,
          this.selectedRatingCycleId
        )
        .subscribe((response) => {
          console.log("response", response);
          if (response && response.length > 0) {
            this.chapterEvals = response;
          }
        });
      this.chapservice
        .getIsitEmployeeStatus(this.activeUser.ipn, this.selectedCycleId)
        .subscribe((sdpStatus) => {
          this.activeUserStatus = sdpStatus;
       if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
                 //do something
            }
        });
    });

【问题讨论】:

  • 内部订阅你希望它是全职订阅还是只执行一次
  • 需要全职执行

标签: angular typescript rxjs-observables


【解决方案1】:

您必须使用forkJoinswitchMap 的组合。

  • 为什么是switchMap? - 因为你有依赖值,只能通过顺序执行来实现。
  • 为什么是forkJoin? - 您可以在此处使用forkJoinmergeMap

代码

this.chapservice.cycle().pipe(
  switchMap((current: any) => 
     forkJoin(
        this.chapService.getChapterEvalWithSkills(
           this.activeUser.ipn,
           this.selectedRatingCycleId
        ),
        this.chapservice.getIsitEmployeeStatus(this.activeUser.ipn, current.ratingCycleId)
     )
  )
).subscribe(([chapterEvals, sdpStatus]) => {
      console.log(chapterEvals, sdpStatus);
      if (chapterEvals && chapterEvals.length > 0) {
        this.chapterEvals = chapterEvals;
      }
      this.activeUserStatus = sdpStatus;
      if (this.activeUserStatus.statusDescription == 'SUBMITTED') {
             //do something
        }
    });
});

【讨论】:

  • 感谢您的回答。为什么我们不能在此使用合并映射?
  • 我收到 2 个错误。!属性 ratingycycleId 不存在类型未知。 2. 类型 OperatorFunction 上不存在属性订阅。知道为什么吗?
  • @mohammedfahimullah 尝试在switchMap 中更新(current: any),检查更新后的答案
  • 属性 'subscribe' 在类型 'OperatorFunction' 上不存在这个错误怎么办?
  • @mohammedfahimullah 检查更新的答案。订阅前缺少右括号:D
猜你喜欢
  • 2022-06-22
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2019-08-20
  • 2021-11-25
相关资源
最近更新 更多