Angular5:批量调用以获取json数组中文件的数据



我有一个数组,其中包含以下格式的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","员工指定":"PRA"},{"id":2,"name":"Peter","员工指定":"MRA"}]

因此,在这里,我每得到30批指定,就需要用该值更新员工记录。

staff.component.ts

for(设i=0;i<=this.stafflength;i++({this.staffService.getStaffDesignator(//应传递30个对象(.subscribe((指示符(=>{//此处传递30个//更新指示符逻辑},(err(=>{

})

}

员工服务.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
}

当您从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... 
}
})

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

步骤1:制作一个由30个批次组成的数组。

步骤2:用于带有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... 
})
}

staff数据视为:

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

并且您的API以请求的相同顺序返回数据,

您可以将员工ID获取为:

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 }
}), {})
);

最新更新