问题
I want to iterate through an array and want to make subsequent api calls , and to display that elements related value
currentRefValue: any = [];
myArray.droppeditem = [];
somearray.forEach(element => {
let objTemp:any = {}
objtemp.receivedValue =
someFunction(element.elementId,element.elementName)
myArray.droppeditem.push(objTemp);
})
someFunction(eId,ename){
let parentObj = this.getExisitingParentObj(eId);
let parentEquip = parentObj.map(equip => equip.entities.filter(entity =>
entity.entities.length > 0)[0])[0];
let ref = this.helperService.getPointId(this.someExisitngObject,
['current', 'desired'], parentEquip.referenceIDs)[0];
let subs = this.siteService.getPointData(ref, 'current')
.pipe(
map(this.helperService.stripHaystackTypeMapping),
)
.subscribe(({ rows }) => {
if (rows.length > 0) {
this.currentRefValue[ename] = rows[0].val;
}
});
//someCalculations
return this.currentRefValue;
}
The subsequent api call(this.siteService.getPointData) expects value from the previous api call(this.helperService.getPointId) and the previous(this.helperService.getPointId) inturn already has parentEquip object . I want to call someFunction from inside foreach loop as I have to get currentRefValue of each element
Html
<div *ngFor="let existingItem of myArray.droppeditem">
<span>existingItem.receivedValue</span>
</div>
回答1:
This doesn't return what you think it does:
objtemp.receivedValue = someFunction(element.elementId,element.elementName)
this.currentRefValue
is always returned before any http-request is finished. Instead inside the subscribe block push data to your array. Here's a simplified sample of your code, since we don't know what all things you do in your code, but it should be handled like this:
this.elements.map(element => {
// do stuff before http-request
this.myService.getPointData().pipe(
map(data => {
// do stuff with received data and then push to array
this.myObj.droppedItem.push({ receivedValue: data[0].val });
})
).subscribe();
});
STACKBLIZ
You could also use forkJoin
to run all these requests in parallel.
来源:https://stackoverflow.com/questions/58130280/making-api-calls-from-inside-foreach-for-every-element-and-getting-values-in-ang