我有一组对象要传递到 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
);
关于node.js - 如何以 Angular 循环多个http post请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668016/