如何在Angular和RxJ中管理多个顺序订阅方法?

Sho*_*fol 0 javascript rxjs typescript angular

我需要拨打两个http服务呼叫,并在订阅另一个http服务呼叫后订阅它们。我的意思是,该操作将是连续的,因为最后两个调用取决于第一个。可以使用RxJs的concatMap处理此操作吗?

我使用嵌套订阅解决了该问题。但是,我认为使用concatMap可以做到。在我搜索的所有示例中,有两个串联的调用。如何合并两个以上的订阅并解决问题。

this.accountService.fetchBranchCodeLength().subscribe(
        data => {
            this.branchCodeLength = +data;


    //Now, I need to call another service to calculate 
    accountNumberLengthWithProductCode//


   this.subscribers.fetchAcoountNumberLength = 
    this.accountService.fetchAccountLengthConfiguration().subscribe(
      accountLength => {
        this.accountNumberLengthWithProductCode = 
            (+accountLength) - (+this.branchCodeLength);});


    //Another same kind of call to calculate 
    SUBGLCodeLength//


   this.subscribers.fetchSUBGLCodeLengthSub = 
     this.glAccountService.fetchSUBGlCodeLength(SUBGlCodeQueryParam)
      .subscribe(length => this.SUBGLCodeLength = 
          (+length.value) - (+this.branchCodeLength)                        
    );
  }
);
Run Code Online (Sandbox Code Playgroud)

Ami*_*ian 5

当您有很多请求时使用Concat映射,但是当它们相似时,这意味着它们将具有相同的输出数据和处理程序,而事实并非如此。因此,您可以使用forkJoin,因为调用之间没有任何依赖关系。

forkJoin(
   this.accountService.fetchBranchCodeLength(),
   this.accountService.fetchAccountLengthConfiguration(),
   this.glAccountService.fetchSUBGlCodeLength(SUBGlCodeQueryParam)
).subscribe(([data, accountLength, length]) => {
   this.branchCodeLength = +data;
   this.accountNumberLengthWithProductCode = (+accountLength) - this.branchCodeLength
   this.SUBGLCodeLength = (+length.value) - this.branchCodeLength;
});
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您不必取消订阅http调用可观察对象,因为它们是有限的(确切地说,仅发出一个事件)。