如何使用 Angular 在一个函数上调用多个 API? [英] How can I call multiple API's on a function with Angular?
问题描述
我需要在一个函数上调用 4 个不同的 API,该函数需要一个接一个地执行,因为我之前的 API 结果将使用下一个调用作为参数.例如:我有一个用于 geo Ip 的调用 API,然后我需要调用另一个 API,我需要传递我从第一次 API 调用中获得的经纬度.
I need to call 4 different API's on a single function which is need to execute one after another as my previous API result will use the next Call as a param. For example: I have a call API for geo Ip, then I need to call an another API which I need to pass lat and long which I have got from first API call.
如何在 angular 4 上完成此任务?
How can I achieve this task on angular 4?
我听说过一些方法,比如 flatmap 和 forkjoin.请问这个方法可以用吗?(我没有任何代码,因为我有点困惑).
I heard about some methods like flatmap and forkjoin. Is this method can use? (I didn't have any code as I am little bit confused).
推荐答案
如果你能用 es6 你就可以用 async 和 await
If you can use es6 you can use async and await
async makeCalls() {
try {
let response1 = await this.http.get(firstEndpointUrl).toPromise();
let secondEndpointUrl = 'someUrl/' + response1.json().id;
let response2 = await this.http.get(secondEndpointUrl).toPromise();
let thirdEndpointUrl = 'someUrl/' + response2.json().id;
let response3 = await this.http.get(thirdEndpointUrl).toPromise();
return response3.json();
} catch (error) {
// handle error
}
}
这篇关于如何使用 Angular 在一个函数上调用多个 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!