如何结合两个相似的HTTP请求返回Rx Observables? [英] How to combine two similar http requests returning Rx Observables?

查看:162
本文介绍了如何结合两个相似的HTTP请求返回Rx Observables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I merge 2 separate http requests into one response(join them)?

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"}]

我需要的是一个具有合并结果的单个数组:

What I need is a single array with the combined results:

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

即,一个可观察到的4个对象,而不是2个可观察到的2个对象.

I.e., one observable of 4 objects, not 2 observables of 2 objects.

推荐答案

我相信您想要forkJoin(它变成 Zip 运算符),它返回一个可观察到的序列,该数组带有一个数组,该数组收集了所有输入序列的最后一个元素:

I believe you want forkJoin (which becomes Zip operator) which returns an observable sequence with an array collecting the last elements of all the input sequences:

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 运算符很感兴趣.

Also you may be interesting in combainLatest operator.

UPD 要获得组合结果,可以使用map和散布运算符:

UPD To get a combined result you may use map and spread operator:

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

这篇关于如何结合两个相似的HTTP请求返回Rx Observables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆