简体   繁体   English

如何结合两个相似的HTTP请求返回Rx Observables?

[英]How to combine two similar http requests returning Rx Observables?

How do I merge 2 separate http requests into one response(join them)? 如何将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()))

I'm getting two arrays back: 我得到两个数组:

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

Ie, one observable of 4 objects, not 2 observables of 2 objects. 即,一个可观测的4个对象,而不是2个可观测的2个对象。

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: 我相信您想要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])
  )

Also you may be interesting in combainLatest operator. 另外,您可能对combainLatest运算符很感兴趣。


UPD To get a combined result you may use map and spread operator: UPD要获得合并结果,可以使用map和spread运算符:

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)
  )
Observable.merge(
  this.http.get(url1).pipe(mergeMap(a => a)), 
  this.http.get(url2.pipe(mergeMap(a => a))  
).subscribe(res => console.log(res.json()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM