Chaining http calls in angular 2 in a for loop

前端 未结 3 746
挽巷
挽巷 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 09:02

    First return the observable from your service method:

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

    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())
    

提交回复
热议问题