在for循环中以角度2链接http调用 [英] Chaining http calls in angular 2 in a for loop
本文介绍了在for循环中以角度2链接http调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码看起来像
//service.ts
addProduct(productId) {
this.http.post('someUrl', ReqData).map(json).subscribe(doStuff);
}
//component.ts
addAllproducts(productsIds) {
productIds.forEach(productId => service.addProduct(productId);
}
我想要的是能够等到每个电话完成才能打电话对于下一个productId,不使用 window.setTimeout
..
What I want is to be able to wait for each call to finish before calling for the next productId, without using window.setTimeout
..
推荐答案
首先从您的服务方法返回observable:
First return the observable from your service method:
addProduct(productId) {
return this.http.post('someUrl', ReqData).map(json).subscribe(doStuff);
}
并使用递归函数并在 subscribe
回调中为数组中的每个项目调用它:
And use a recursive function and call it in the subscribe
callback for each of the items in your array:
let loop = (id: number) => {
service.addProduct(id)
.subscribe((result) => {
// This logic can be modified to any way you want if you don't want to mutate the `producIds` array
if (productIds.length) {
loop(productIds.shift())
}
})
}
loop(productIds.shift())
这篇关于在for循环中以角度2链接http调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文