Search code examples
angularangular5angular6lodash

Angular5: batch calls to get data for a filed in a json array


I have an array with json data in the below format

staff = [
{ "id"   : 1,
   "name" : "Robert"
},
{ "id"   : 2,
   "name" : "Peter"
}
]

I am trying to get the designation of these people. There is an API which accepts group of ids. I am trying to get designations in batches of 30. i.e send first 30 objects and get their designations and go on.. I tried keeping a for loop and pass 30 objects but unsuccessful.

Designation API gives data in the below format.

[
  {
    "staffId": "26",
    "designation": "PRA"
  },
  {
    "staffId": "25",
    "designation": "MRA"
  }
]

Result json

staff = [ { "id" : 1, "name" : "Robert", "staffDesignation": "PRA" }, { "id" : 2, "name" : "Peter", "staffDesignation": "MRA" } ]

So here for every 30 batches of designations that I get, I need to update the staff record with that value.

staff.component.ts

for (let i = 0; i <= this.staff.length; i++) { this.staffService.getStaffDesignator(//should pass 30 objects).subscribe((designator) => { //Here pass 30 objects //update designator logic }, (err) => {

})

}

staff.service.ts

getStaffDesignator(staff)
{

    staff.forEach((staff, index) => {
      if (index === 0) {
        url = url + `?contactId=${staff.id}`;
      }
      else {
        url = url + `&contactId=${staff.id}`
      }
    }) //loop through the objects to get the staff id to pass to the APIcall

    return this.http.get(url, this.options)
      .map((res: Response) => {
        return res.json();
      })  //API call to get designations for staff

}

Solution

  • While you get res from API call then you can start to work in filter array process.

    var filterArray = [];
    
    this.http.post(url , param , header , function(err , response) => {
        // First way is to use map
        // You can use for loop 
        for(let i = 0 i < response.length ; i++){
             var obj = {
                 id: response[i].staffId,
                 name: response[i].name,
                 staffDesignation: response[i].designation,
             }
             this.filterArray.push(obj);
    
             // Now you can call next API for another batch... 
        }
    })
    

    In this case , I suggest you can use this below structure.

    step1 : Make a array of 30 batches.

    step2 : Use for loop with Observable.

    for(let i = 0 ; i < this.array.length ; i++){       //Each i has batch of 30.
    
         // Hear observable will work as a promise in for loop to make call in sync.
         return new Observable((observer) => {
              return http.post(url , param , option)...
    
             //Once you got data from API use my above code to filter your
             // Key and value from res. 
    
            observable.next();
            observable.complete(); // It will go for call next batch... 
         })
    }