Chaining API calls with Observables in Angular 2 & 4

Yonathan Meguira
Jul 27, 2017 · 2 min read

When building web application I have encountered this issue countless times. You have to wait for API calls to come back to perform so other actions.

Let’s say we are trying to retrieve github users using git API and that for each user we want to get the number of associated repositories. How would we go about that ? well there are several ways

Using mergeMap

as you can see here we use two operators: map and mergeMap.

Map operator will execute an action for each of the user retrieved: it will modify the outcome.

Here mergeMap help us by pulling out each user and subscribing to an inner observable (the repos for each user). We now have two nested observables and our code is a bit more condensed and readable.

Using forkJoin

Here forkJoin will subscribe to all the calls in parallel, and wait for them return to give them back to you.

Hence it returns an array of data with all the results of all the calls.

So if you want to chain calls you should be using mergeMap (as you want for example the repositories for each user), if you need two independent calls to come back and to dispose of their result at the same time then you should be going with forkJoin.

Yonathan Meguira

Written by

Front End Developer | Israel

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade