Angular 5:批量调用以获取 json 数组中字段的数据

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

我有一个包含 json 数据的数组,格式如下

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

我正在尝试获取这些人的名称。有一个 API 接受一组 ID。我正在尝试以 30 个为一组获取指定。即发送前 30 个对象并获取它们的指定并继续。我尝试保留一个 for 循环并传递 30 个对象但不成功。

指定 API 给出以下格式的数据。

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

结果json

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

因此,对于我获得的每 30 批指定,我需要使用该值更新员工记录。

staff.component.ts

for (设 i = 0; i <= this.staff.length; i++) { this.staffService.getStaffDesignator(//应该传30个对象).subscribe((designator) => { //这里传30个对象 //更新指示器逻辑 }, (错误)=> {

})

}

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

}

将您的 staff 数据视为:

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

您的 API returns 数据的顺序与请求的顺序相同,

您可以获取 staffIds 为:

staffIds = staff.map(item => item.id);

调用 API 并获得 response 后,您可以将响应与 staff 数组合并,如下所示:

resultingArray = Object.values(
  [...staff, ...response]
  .reduce((r, { staffId, id = staffId, ...rest }) => ({
    ...r,
    [id]: { id, ...r[id], ...rest }
  }), {})
);

当您从 API 调用中获得 res 时,您就可以开始处理过滤器数组进程了。

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... 
    }
})

在这种情况下,我建议您可以使用下面的结构。

step1 : 制作一个包含 30 个批次的数组。

step2 : 使用 for 循环 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... 
     })
}