首页 > 解决方案 > 订阅多个可观察对象,同时保持对函数参数的引用

问题描述

我有一个字符串数组的输入,用于我想从服务器接收的枚举:

enumList = ['somethin','branch','country', 'serviceType', 'thatandthis'];

然后,我有一个通用的 http-service 方法,该方法将enumList字符串作为参数并返回该 Enum 服务的 HttpClient observable:

this.webApi.getEnumByName('somethin','en').subscribe((res)=>{/*do something*/})
this.webApi.getEnumByName('branch','en').subscribe((res)=>{/*do something*/})...

我不是将两者组合成一个循环

   for (const item of this.enumList) {
      this.webApi.getEnumByName(item).subscribe((res: any) => {
          this.enums[item] = res;
      });
    } 

但这不好......我希望订阅在所有订阅都已解决后仅完成一次,同时 使用从 this.webApi.getEnumByName(item)、concat 或forkJoin 将不起作用,因为它们不会保留对响应的关联字符串/键/令牌的引用,例如 enumList 中的字符串。



这些连接的 observables 的最终结果应该是:

{
    'somethin':{respopnse...},
    'branch':{respopnse...},
    'country':{respopnse...},
    'serviceType':{respopnse...},
    'thatandthis':{respopnse...}
}

打破我的头脑将应用 rxjs 解决方案

标签: rxjsangular8angular9rxjs-pipeable-operatorsrxjs-observables

解决方案


您可以创建一个函数来传递 this.enumList 并仍然获得相同的引用

function getResponse(enum){
  return forkJoin(....).subscribe(....)
}

或者

forkjoin this.enumList 和 http 调用列表

forkJoin(of(this.enumList), forkJoion(httpcall1,htttpcall2))
.subscribe([enum,responsesArray]=>....)

推荐阅读