【问题标题】:Issue with asynchronous angular requests异步角度请求的问题
【发布时间】:2021-06-13 10:45:21
【问题描述】:

如何处理 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
    })
}

【问题讨论】:

标签: javascript angular typescript rxjs5


【解决方案1】:

您的代码似乎运行良好,并且您正确使用了订阅功能。您记录undefined 的原因是console.log(array) 行在'someUrl'+team 的get 请求返回值之前被调用。要检查这一点,您可以在订阅范围内移动 console.log(array) 行(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);
}

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多