Chaining http calls in angular 2 in a for loop

前端 未结 3 748
挽巷
挽巷 2020-12-18 08:36

I have some code that looks like

//service.ts

addProduct(productId) {
   this.http.post(\'someUrl\', ReqData).map(json).subscribe(doStuff);
}

//component.         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 08:55

    You can use the Observable.merge(). Try something like that

    addProduct(productId):Observable {
       return this.http.post('someUrl', productId);
    }
    
    addAllproducts(productsIds) {
       let productedsObservable:Observable[]=[];
       for(let productID in productsIds){
        this.productedsObservable.push(this.addProduct(productID));
       }
       return Observable.merge(productedsObservable)
    }
    

    You need to subscribe to the requested function for it the execute the http request. You can read more about combination operators (like merge) here

提交回复
热议问题