[英]Issue with asynchronous angular requests
如何處理 angular 中的異步調用。 我知道由於異步性質,我的數組未定義,但我該如何解決它
private fetchData(id){
var array = [];
this.httpClient.get('someUrl/'+id).subscribe((organisation)=>{
console.log(organisation.teams); // ['team1','team2','team3']
organisation.teams.forEach((team)=>{
this.httpClient/get('someUrl/'+team).subscribe((teamData)=>{
array.push(teamData);
})
})
console.log(array); // undefined
})
}
您的代碼似乎工作正常,並且您正確使用了訂閱功能。 您記錄undefined
的原因是console.log(array)
行在對'someUrl'+team
的獲取請求返回值之前被調用。 要檢查這一點,您可以將console.log(array)
行移動到訂閱的 scope 內array.push(teamData)
行所在的位置)。
使用更少縮進的更現代的編寫方式是使用 async/await:
private async fetchData(id){
var array = [];
let organisation = await this.httpClient.get('someUrl/'+id).toPromise();
console.log(organisation.teams); // ['team1','team2','team3']
let teamData;
organisation.teams.forEach((team)=>{
teamData = await this.httpClient/get('someUrl/'+team).toPromise()
array.push(teamData);
})
console.log(array);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.