Search code examples
angularhttpclient

Angular Loop over httpClient


I have a grid of multiple rows and I am doing a bulk action 'Ex: deletion for multiple rows on 1 click' so I am looping over the httpClient reuest. So if I have 3 rows, When the 3rd request is excuted successfully I wanna popup a single toaster saying 'Saved Successfully'. The problem now is that I am putting that toaster code inside the for loop so it shows up 1 every successful request.At the same time If I put it outside the loop it will be triggered before the subscription ends.

for(let i=0;i<this.selectedData.length;i++){
  this.service.delete(
    this.multipleSelected[index].id
  )
  .subscribe(res => {
    this._ToasterService.success('Successfully Changed');
     
  });
}

Solution

  • Use forkJoin

    const deleteRequests: any[] = [];
    for (let i = 0; i < this.selectedData.length; i++) {
      deleteRequests.push(this.service.delete(this.multipleSelected[index].id));
    }
    
    forkJoin(deleteRequests).subscribe(res => {
      this._ToasterService.success('Successfully Changed');
    });