【问题标题】:async API Request using the Angular 6使用 Angular 6 的异步 API 请求
【发布时间】:2018-12-06 12:14:56
【问题描述】:

根据我的要求,我需要使用 Angular 6 Httpclient 发送异步请求。
谁能解释一下如何发送异步请求?

组件中的循环调用:

REST API 服务中的函数:

现在,所有请求都在进行中。但我希望在完成第一个请求后,第二个请求应该去等等。

请告诉我这在 Angular 6 中是否可行?

请试着给我一些好的例子。

this.pressArray.forEach(function(field_value, field_index){
  restAPI.CallAddPageBlock(formData, '', id).subscribe(response2 => {
    content_blocks.push(response2.id);
  });
});


CallAddPageBlock(formData, tickets='', id): Observable<any> {
  var full_url = this.baseUrlContent + 'Hub_PageBlock_C/assets/';
  if(id!=0){
    full_url = full_url+id
  }
  return this.http.post(full_url, formData, this.httpOptionsJson).pipe(); 
}

【问题讨论】:

标签: angular angular6


【解决方案1】:

您可以使用 async/await 和 Promise 来简化此操作。使用 toPromise() 将 observable 转换为 Promise

async doSomethingAsync() {
  for(var item of this.pressArray) {
    let response2 = await restAPI.CallAddPageBlock(formData, '', id).toPromise();
    content_blocks.push(response2.id);
  }
}

没有必要在最后的CallAddPageBlock中调用pipe

有关 async/await 的更多信息,另请参阅这个出色的答案并滚动到标题 ES2017+: Promises with async/await

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2018-03-04
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多