javascript - 如何组合两个返回 Rx Observables 的相似 http 请求?

标签 javascript angular typescript rxjs observable

如何将 2 个单独的 http 请求合并为一个响应(将它们合并)?

Observable.merge(
  this.http.get(url1), // [{"city":"New York"},{"city":"Chicago"}]
  this.http.get(url2)  // [{"city":"Washington"},{"city":"Detroit"}]
).subscribe(res => console.log(res.json()))

我得到了两个数组:

[{"city":"New York"},{"city":"Chicago"}],
[{"city":"Washington"},{"city":"Detroit"}]

我需要的是一个包含组合结果的数组:

[{"city":"New York"},{"city":"Chicago"},{"city":"Washington"},{"city":"Detroit"}]

即,4 个对象的 1 个可观察值,而不是 2 个对象的 2 个可观察值。

最佳答案

我相信你想要 forkJoin (变成 Zip 运算符),它返回一个可观察的序列,其中包含一个收集所有输入序列的最后元素的数组:

combine(): {
  return Observable.forkJoin(
    this.http.get(url1).map(res => res.json()),
    this.http.get(url2).map(res => res.json())
  )
}

...

  this.combine().subscribe(result => 
    console.log(result[0], result[1])
  )

您可能对 combainLatest 感兴趣运算符。

<小时/>

UPD要获得组合结果,您可以使用map和展开运算符:

combine(): {
  return Observable.forkJoin(
    this.http.get(url1).map(res => res.json()),
    this.http.get(url2).map(res => res.json())
  )
  .map((data: any[]) => ([...data[0], ...data[1]])
}

...

  this.combine().subscribe(result => 
    console.log(result)
  )

关于javascript - 如何组合两个返回 Rx Observables 的相似 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51003275/

相关文章:

javascript - Webpack url-loader 中的某些图像出现 404s

javascript - 如何加载 .js 文件 'locally' ?

Angular 2上传文件到FTP服务器

javascript - 点后仅保留两位小数( Angular )

javascript - 如何在 FullCalendar 中禁用拖动,但保留单击时间段的能力并使 "placeholder"约会仍呈现

javascript - 在 Chart.js 中更改工具提示颜色

angular - NativeScript + Angular - 预览中的新项目错误 : Type AppRoutingModule does not have 'ngModuleDef' property

javascript - 为loadChildren提供函数有什么好处?

带有自定义事件的 Angular 4 dispatchEvent

angular - 在 Angular2 中使用移动事件