Reputation: 183
I need to make nested http calls in angular 4, Here is my scenario, The first call is a search api call which returns list of IDs and then I need to loop through the IDs and make another api call using each ID to get details. What is the best method to achieve this using angular 4.
Upvotes: 0
Views: 1286
Reputation: 6825
You can achive this using RxJs Switch Method, by doing something like this:
http.get(/*you params here*/).switchMap(firstResponse => {
let idsArray = extractArrayFromResponse(firstResponse);
// Loop through Array
let arrayOfObservables = idsArray.map(id => http.get(/*other params*/));
// Now you need to map it to Obervable of arrays
let obervableOfArrays = arrayOfObservables.merge().toArray();
return obervableOfArrays;
})
Please check out the documentation of Reactive Extensions
here:
http://reactivex.io/documentation/operators.html
And you are probably using it's JS implementation that can be found here: https://github.com/reactivex/rxjs
Also, it might be useful in your case to check out forkJoin
operator as suggested by @cyrix. Find JS implementation here:
http://reactivex.io/documentation/operators/zip.html
Upvotes: 4