j809809jkdljfja
j809809jkdljfja

Reputation: 807

How to combine two similar http requests returning Rx Observables?

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.

Upvotes: 1

Views: 766

Answers (2)

dhilt
dhilt

Reputation: 20834

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

Upvotes: 1

John
John

Reputation: 4611

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

Upvotes: 1

Related Questions