angular - 使用 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();
}
解决方案
您可以使用 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);
}
}
没有必要pipe
在CallAddPageBlock
最后打电话。
有关 async/await 的更多信息,另请参阅这个出色的答案并滚动到标题ES2017+: Promises with async/await。
推荐阅读
- python - “Int”对象在 Discord.py 命令上没有属性“id”错误
- javascript - Onclick 事件谷歌地图
- angular - 嵌套多维数组角度模型
- bash - Bash 脚本:错误,文件意外结束
- spring - 自定义 Spring Zuul 动态路径
- git - 如何将 repo 的一个分支 fork 到一个新的存储库中?
- here-api - HERE api 正在返回 PermissionError
- react-native - 嵌入自定义 React-Native 组件库
- c++ - 无法在 Linux Minut 中运行简单的 OpenGL 程序
- docker-compose - 执行脚本 docker-compose 失败