简体   繁体   中英

Nested HTTP calls in angular 4

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM