Search code examples
angularobservablesynchronousbulk

Angular 4 - How to make bulk http syncronous requests


I have in my Angular 4 App a formulary to upload data. This data comes in a array of JSON elements and I loop over it to make an HTTP PUT request through an observable.

If a little set of elements are going to be upload everything works fine, but sometimes input can be 1000+ elements large.

As I'm using observables, all the request are made in a synchronous way, so at the same time. That makes the backend literally crash if the number of elements is big enough.

I need to make the HTTP requests one by one but I don't know how to do it. ¿Could you help me?

Service function:

putIp(ip, data): any {
const url = `${this.IpUrl}/${ip}`;
return this.authHttp.put(url, data, {headers: this.headers});}

Component function:

       publishIps(): void {
     console.log("Publishing Ips")

     for (let _i = 0; _i < this.ipsInTable.length; _i++) {
         this.ipsInTable[_i].treated = true;
         this.ipService.putIp(this.ipsInTable[_i].id, this.ipsInTable[_i].json)
         .catch(err => {
           this.ipsInTable[_i].result = false;
           this.ipsInTable[_i].message = "Error";
           return Observable.throw(this.errorHandler(err));
         })
         .subscribe((data) => {
            // Doing some stuff
         });
     }
   }

Solution

  • I would tweak the backend to accept an array of objects. Then you just do one request.

    If that's not an option, and you want to submit the request one at a time, here's a different approach to your controller code:

    publishIp(_i: int): void {
       if (_i < this.ipsInTable.length) {
    
         this.ipsInTable[_i].treated = true;
         this.ipService.putIp(this.ipsInTable[_i].id, this.ipsInTable[_i].json)
         .catch(err => {
           this.ipsInTable[_i].result = false;
           this.ipsInTable[_i].message = "Error";
           return Observable.throw(this.errorHandler(err));
         })
         .subscribe((data) => {
           _i++;
           publishIp(_i);           
            // Doing some stuff
         });
      }
    }
    publishIps(): void {
     console.log("Publishing Ips");
    
     publishIp(0);     
    }
    

    Disclaimer: I just typed this into stackoverflow. You may have to fix some typos.