How to combine the results of two observable in angular?

A great way to do this is to use the rxjs forkjoin operator (which is included with Angular btw), this keeps you away from nested async function hell where you have to nest function after function using the callbacks.

Here’s a great tutorial on how to use forkjoin (and more):

https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

In the example you make two http requests and then in the subscribe fat arrow function the response is an array of the results that you can then bring together as you see fit:

let character = this.http.get('https://swapi.co/api/people/1').map(res => res.json());
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1').map(res => res.json());

Observable.forkJoin([character, characterHomeworld]).subscribe(results => {
  // results[0] is our character
  // results[1] is our character homeworld
  results[0].homeworld = results[1];
  this.loadedCharacter = results[0];
});

The first element in the array always corresponds to the first http request you pass in, and so on. I used this successfully a few days ago with four simultaneous requests and it worked perfectly.

Leave a Comment