Skip to content

Instantly share code, notes, and snippets.

@killerchip
Created January 1, 2018 06:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/d67f1095d95ca4dc979f849d36c9c57e to your computer and use it in GitHub Desktop.
Save killerchip/d67f1095d95ca4dc979f849d36c9c57e to your computer and use it in GitHub Desktop.
Angular tip: RxJS - Gather up info from APIs

Gather up info from APIs

In this example we gather up information from two different API endpoints, combine them and present them as one object to the subscriber.

Explanation:

  • We create an observable that queries the 1st endpoint.
  • With mergeMap operator we trigger query for the 2nd endpoint. The 2nd query depends on the results of the 1st query.
  • Finally we combineLatest the two observables into one that emits the combination of the two.
...
const postArray = this.getPosts();

const comments = postArray.pipe(
  mergeMap(posts => this.http.get(`https://jsonplaceholder.typicode.com/posts/${posts[1].id}/comments`))
);

const latest = combineLatest (postArray, comments, (posts, cmnt) => {
  return {a: posts, b: cmnt};
})

latest.subscribe(data => {
  this.posts = data.a;
  this.comment = data.b;
});

Note: We use RxJS 5.5 which now use the 'lettable' operators.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment