Reputation: 59
I'm trying to chain two http calls. The first one returns a set of records and then I need to get finance data for each of them.
flightRecordService.query().$promise.then(function (flightRecords) {
$scope.flightRecords = flightRecords;
for (var i = 0; i < $scope.flightRecords.length; i++) {
$scope.flightRecords[i].financeDocument =
financeDocumentService
.isReferencedDocumentIdCompensated({
id: $scope.flightRecords[i].id
}).$promise.then(
function (data) {
return ({
'isCompensated': data.headers['compensated']
});
}
);
console.log($scope.flightRecords);
}
});
This is the FlightRecord object:
$$hashKey: "object:27"
aircraft: {id: 100, registration: "LV-OEE", model: "152", status: "ACTIVE", brand: "Cessna", …}
amountOfHours: 1
canceled: false
closed: false
crew: [Object] (1)
destiny: null
endFlight: "2017-01-06T20:54:05.296"
financeDocument: d
--> $$state: {status: 1, value: {isCompensated: "false"}}
--> d prototipo
id: 100
landings: 0
nature: "LDI"
opened: true
origin: null
purpose: "VP"
startFlight: "2017-01-06T19:44:05.296"
status: "OPENED"
type: "ENT"
financeDocument object has not the structure I expect... I need a the following format:
...
endFlight: "2017-01-06T20:54:05.296"
financeDocument: { isCompensated: "false" }
id: 100
...
What I need to change to get that?
Thanks a lot!!
Upvotes: 1
Views: 73
Reputation: 164796
What you'll want to do is modify each "flight record" entry when you've retrieved the extra details. You'll also probably want to use $q.all
to signal to the caller that the operation is complete.
const promise = flightRecordService.query().$promise.then(flightRecords => {
return $q.all(flightRecords.map(flightRecord => {
return financeDocumentService.isReferencedDocumentIdCompensated({
id: flightRecord.id
}).$promise.then(data => Object.assign(flightRecord, {
isCompensated: data.headers.compensated
}))
}))
})
promise.then(flightRecords => {
$scope.flightRecords = flightRecords
})
Upvotes: 2
Reputation: 22911
Why not just set it on the original object?
flightRecordService.query().$promise.then(function (flightRecords) {
$scope.flightRecords = flightRecords;
for (var i = 0; i < $scope.flightRecords.length; i++) {
(function(record) {
financeDocumentService
.isReferencedDocumentIdCompensated({
id: $scope.flightRecords[record].id
}).$promise.then(
function (data) {
$scope.flightRecords[record].financeDocument = {
'isCompensated': data.headers['compensated']
}
});
})(i)
console.log($scope.flightRecords);
}
});
Upvotes: 1
Reputation: 2398
You are trying to set the financeDocument property synchronously using a Promise. You need to set the variable in the success callback of the promise.
Upvotes: -1