node.js - 如何以角度循环多个http post请求?
问题描述
我有一组要传递给一次接受一个对象的 mongoDB 模型的对象,我尝试循环 http post 请求,但由于它是异步的,因此不起作用。还有其他解决方案吗?
for (let entry of ingredients) {
const body = JSON.stringify(entry);
console.log(body);
const headers = new HttpHeaders({'Content-Type': 'application/json'});
return this.http.post('http://localhost:3000/shopping-list', body, {headers: headers})
.catch((error: Response) => Observable.throw(error));
}
谢谢
解决方案
如果您想连续提出请求,请尝试concatMap
Observable.from(ingredients)
.concatMap(entry => this.http.post('http://localhost:3000/shopping-list', entry))
.subscribe(
response => console.log(response), //do something with responses
error => console.error(error), // so something on error
() => console.info("All requests done") // do something when all requests are done
);
推荐阅读
- r - 通过 2 个变量对许多数据集 R 进行聚类
- mysql - 按长度(城市)排序 ASC 限制 1;在 MYSQL 中不显示第一项
- amazon-web-services - AWS Athena 与 Power BI 服务
- r - 按组完成时 data.table 中的 na.locf
- react-native - React Native 中的导航转到错误的页面
- c# - 搜索多个列表并更新另一个列表中的字段
- python - 打印数字表(模式)的任务
- .htaccess - .htaccess 站点地图重写/重定向
- docker - 连接到专用 Docker 机器时如何默认使用 Docker Compose 生产配置?
- reactjs - axios 删除 API 不起作用(使用 JSON 服务器)