node.js - 如何以 Angular 循环多个http post请求?

标签 node.js angular loops asynchronous

我有一组对象要传递到 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/

相关文章:

javascript - 无法将js加载到MongoDB中

javascript - 将 HTML 表单输入分配给 Node JS 中的变量

javascript - 使 div 及其所有子项忽略父类样式

Javascript 将 JSON 数据解析为多个变量,将单独的记录存储在内存中

node.js - Node Sass 找不到当前环境的绑定(bind) : Linux 64-bit with Node. js 7.x

node.js - 如何使用 vows.js 运行清理?

Angular 2 + OnPush : Change detection does not work on pouchdb callbacks

c - 有什么建议或改进吗?

当 number > 10 时,Javascript For 循环中断。有指针吗?

JavaFX ToggleButton 进入和退出无限循环