How to combine two similar http requests returning Rx Observables?

妖精的绣舞 提交于 2020-02-07 05:35:05

问题


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

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

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


回答1:


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

Also you may be interesting in combainLatest operator.


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



回答2:


Observable.merge(
  this.http.get(url1).pipe(mergeMap(a => a)), 
  this.http.get(url2.pipe(mergeMap(a => a))  
).subscribe(res => console.log(res.json()))


来源:https://stackoverflow.com/questions/51003275/how-to-combine-two-similar-http-requests-returning-rx-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!