代码之家  ›  专栏  ›  技术社区  ›  Jason Spradlin

将外部和内部可观测结果合并为下一个地图方法的单个参数(数组)

  •  1
  • Jason Spradlin  · 技术社区  · 6 年前

    我想做的和combinelatest类似,但是第二个(内部)可观测的取决于第一个的响应

    ajax.get('/first-url')
      .map(res => new Thing(res.response)
      .someMap(thing => 
        ajax.get(`/second-url?code=${thing.code}`)
          .map(res => new OtherThing(res.response))
      ).map(([firstThing, secondThing]) => console.log(firstThing, secondThing))
    

    本质上,我希望能够将这两个结果合并到一个数组中,这些结果是我可以用来做第三件事的。

    我的目标是获取数据A和数据B,因为我需要它们都执行某个操作,而获取数据B依赖于已经有了数据A。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jason Spradlin    6 年前

    我可以通过以下步骤来完成这项工作:

    ajax.get('/first-url')
      .map(res => new Thing(res.response)
      .mergeMap(firstThing=> 
        ajax.get(`/second-url?code=${firstThing.code}`)
          .map(res => new OtherThing(res.response))
          .map(secondThing => [firstThing, secondThing])
      ).map(([firstThing, secondThing]) => console.log(firstThing, secondThing))
    

    从本质上讲,在第二个可观测数据的响应中,返回我想要在外部可观测数据中使用的确切数组 .map

    这似乎是RXJS处理这一问题的理想方式。在RXJS的5.x版本中,有一个叫做结果选择器的东西,它可以作为第二个参数传入以创建类似的东西(它看起来很像最后一个内部 地图 )但对于RXJS V6.0,这似乎已被弃用:

    https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#howto-result-selector-migration