首页 > 解决方案 > 如何以角度循环多个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));

}

谢谢

标签: node.jsangularloopsasynchronous

解决方案


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

推荐阅读