angular 4 中的嵌套 HTTP 调用

Nested HTTP calls in angular 4

我需要在 angular 中进行嵌套的 http 调用 4,这是我的场景, 第一个调用是搜索 api 调用,其中 returns ID 列表然后我需要遍历 ID 并使用每个 ID 进行另一个 api 调用以获取详细信息。使用 angular 4.

实现此目的的最佳方法是什么

您可以使用 RxJs 切换方法实现此目的,方法如下:

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;
})

请在此处查看 Reactive Extensions 的文档: http://reactivex.io/documentation/operators.html

您可能正在使用它的 JS 实现,可在此处找到: https://github.com/reactivex/rxjs

此外,按照@cyrix 的建议检查 forkJoin 运算符可能对您的情况很有用。在这里找到 JS 实现: http://reactivex.io/documentation/operators/zip.html