如何以角度循环多个http post请求?

时间:2018-06-03 15:28:32

标签: 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));

}

谢谢

1 个答案:

答案 0 :(得分:3)

如果您想要连续发出请求,请尝试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
    );