首页 > 解决方案 > 使用 Angular 6 的异步 API 请求

问题描述

根据我的要求,我需要使用 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(); 
}

标签: angularangular6

解决方案


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

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

没有必要pipeCallAddPageBlock最后打电话。

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


推荐阅读