如何在AngularJS中链接两个http调用?

时间:2017-06-30 01:19:55

标签: javascript angularjs json

我正在尝试连接两个http调用。第一个返回一组记录,然后我需要为每个记录获取财务数据。

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

这是FlightRecord对象:

$$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对象没有我期望的结构......我需要以下格式:

...
endFlight: "2017-01-06T20:54:05.296"
financeDocument: { isCompensated: "false" }
id: 100
...

我需要改变什么来获得它?

非常感谢!!

3 个答案:

答案 0 :(得分:2)

当您检索到额外的详细信息时,您要做的是修改每个“航班记录”条目。您还可能希望使用$q.all向呼叫者发出操作已完成的信号。

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

答案 1 :(得分:1)

为什么不将它设置在原始对象上?

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

答案 2 :(得分:-1)

您正尝试使用Promise同步设置financeDocument属性。您需要在promise的成功回调中设置变量。