Tom Barat Tom Barat - 1 year ago 193
HTTP Question

consecutive rest API http calls angular 4

i looked for answers here but found none so i will go ahead and try to explain my situation as clearly as i can in hope that i get one.

Here is the situation : I am building an angular 4 SPA that consumes a rest API backend.
In one of my component i have to fetch several sets of data from the backend (from different methods), and i need to have all these different sets of data to display a chart in my component.

If i just make consecutive http calls in my Init method and then call my process_data method, angular does not wait for all http responses before it calls the processing method. Thus the method is called when all needed data is not necessarily there yet, which can cause errors.

The solution i have right now : The fix i implemented for the time being is the following :

  • I make a first http request, to which i subscribe.

  • In this subscription i make the second http request, to which i also subscribe

  • And so on for each subsequent http request

  • In the last .subscribe() i call my processing method.

The result being a big Init method that is quite hard to read/debug because of all the nested http requests.
So the fix works but it is ugly and will be hard to reuse, which is a serious issue since i am developing this for a company. Which brings me to the...

Question : Is there a better (cleaner/standard/good practice) way of achieving the same result ?

TL;DR : Is there a good way of making several consecutive http requests and wait for all to be completed (and wait for the response) before proceeding ?

notes : Though i am developing this SPA for a company, i am only an intern (thus, still at school, still learning the ropes). In addition to not being a real engineer yet i am also new to angular and web development in general.Of course, i apologize if the answer to my question is obvious.

Secondly, english is not my native language so i also apologize for any english-related mistakes in my post.

I thank you all in advance for your answers.

Answer Source

I believe you will find what you are looking for in Flatmaps or the other solutions found in this great tutorial.

Flatmaps will help you make your multiple HTTP requests linear.

To quote the official documentation:

transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download