如何使用Angular在一个函数上调用多个API? [英] How can I call multiple API's on a function with Angular?
问题描述
我需要在一个函数上调用4个不同的API,该函数需要一个接一个地执行,因为我以前的API结果将使用下一个Call作为参数.例如:我有一个针对geo Ip的调用API,然后我需要调用另一个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.
如何在角度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屋!