【问题标题】:subscribing to multiple observable while keeping reference to function parameters订阅多个可观察对象,同时保持对函数参数的引用
【发布时间】:2020-09-08 01:14:05
【问题描述】:

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

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

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

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

但这并不好...... 我想要一个在所有订阅都解决后只完成一次的订阅,同时保留对关联 item string 的引用

使用从 this.webApi.getEnumByName(item) 返回的 observables 数组,concat 或 forkJoin 将不起作用,因为它们不会保持对响应的关联字符串/键/令牌的引用,例如枚举列表中的字符串。

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

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

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

【问题讨论】:

    标签: rxjs angular8 angular9 rxjs-pipeable-operators rxjs-observables


    【解决方案1】:

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

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

    forkjoin this.enumList 和 http 调用列表

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

    【讨论】:

      【解决方案2】:

      如果我理解你的问题,你可能需要考虑这样的事情。

      首先你用这样的函数构建一个 Observable

      function obsFromItem(item) {
         return this.webApi.getEnumByName(item).pipe(
            tap(res => this.enums[item] = res),
         )
      }
      

      上面的逻辑说,一旦getEnumByName 通知它的结果,结果就会被设置到正确的项目的this.enums 中。

      现在你有了一个类似的函数,你可以像这样创建一个 Observables 数组来传递给forkJoin

      arrayOfObs = enumList.map(item => obsFromItem(item))
      forkJoin(arrayOfObs).subscribe()
      

      forkJoin(arrayOfObs) 发出通知时,这意味着通过obsFromItem 构建的所有Observables 都已发射,因此this.enums 应正确填充。

      forkJoin 为您提供并行执行。如果您将forkJoin 替换为concat,您将获得顺序执行。

      In this article 你可能会发现一些典型的 Obaservables 与 http 调用的使用模式。

      【讨论】:

        【解决方案3】:

        您可以像这样将多个可观察对象组合在一起:

        forkJoin(enumList.reduce<any>((result, key) => {
          result[key] = this.webApi.getEnumByName(key,'en');
          return result;
        }, {})).subscribe(allTogether => {
          // allTogether.somethin;
          // allTogether.branch;
          // ...
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多