[英]How can I call multiple API's on a function with Angular?
我需要在一個函數上調用4個不同的API,這需要一個接一個地執行,因為我以前的API結果將使用下一個Call作為參數。 例如:我有一個針對geo Ip的調用API,然后我需要調用另一個API,該API需要傳遞從第一次API調用獲得的經度和緯度。
如何在角度4上完成此任務?
我聽說過一些方法,例如flatmap和forkjoin。 請問這種方法可以使用嗎? (我沒有任何代碼,因為我有點困惑)。
您可以執行以下操作:
this.http.get('/api/people/1').subscribe(character => {
this.http.get(character.homeworld).subscribe(homeworld => {
character.homeworld = homeworld;
this.loadedCharacter = character;
});
});
因此,這里基本上是在鏈接http調用。 首先,我們要求從/ api / user / 1獲取用戶。 加載后,我們會再次請求獲取該特定角色的家園。 一旦獲得了家庭世界,便將其添加到角色對象,並在組件上設置了loadCharacter屬性,您可以在此處對4個https調用執行類似的操作。
您可以使用mergeMap運算符示例執行此操作:
this.http.get('./customer.json')
.map((res: Response) => res.json())
.mergeMap(customer => this.http.get(customer.contractUrl))
.map((res: Response) => res.json())
.subscribe(res => this.contract = res);
更多信息可以在這里找到
如果可以使用es6,則可以使用async和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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.