组合多个$ http调用的数据

时间:2017-12-28 14:25:45

标签: angularjs

我有3个api端点

  1. / getAccount返回
  2. [{"id":"1", "name":"Bank 1", "starting_balance":"0.00"},{"id":"2", "name":"Bank 2", "starting_balance":"10.83"}]加入$scope.acc

    1. / getExpense返回
    2. [{"id":"1", "amount":"400.00"},{"id":"2", "amount":"500.00"}]加入$scope.expense

      1. / getIncome返回
      2. [{"id":"1", "amount":"1000.00"},{"id":"2", "amount":"1000.00"}]加入$scope.income

        我不知道如何组合这三个数据。这是我的HTML代码:

        <tr>
           <td>Account Name</td>
           <td>Starting Balance</td>
           <td>Income</td>
           <td>Expense</td>
        </tr>
        <tr ng-repeat="a in acc">
           <td>{{a.name}}</td>
           <td>{{a.starting_balance}}</td>
           <td></td>
           <td></td>
        </tr>
        

2 个答案:

答案 0 :(得分:1)

使用map运算符组合数组。

演示

&#13;
&#13;
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.income = [{"id":"1", "amount":"1000.00"},{"id":"2", "amount":"1000.00"}]

$scope.expense = [{"id":"1", "amount":"400.00"},{"id":"2", "amount":"500.00"}]

$scope.acc = [{"id":"1", "name":"Bank 1", "starting_balance":"0.00"},{"id":"2", "name":"Bank 2", "starting_balance":"10.83"}] 

$scope.arr = $scope.acc.map((item) => {
    var exp = $scope.expense.find((ex) => ex.id === item.id)
    var inc = $scope.income.find((ins) => ins.id === item.id)
    return {
      acc : item,
      inc : inc,
      exp : exp
    }
  })
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
<tr>
   <td>Account Name</td>
   <td>Starting Balance</td>
   <td>Income</td>
   <td>Expense</td>
</tr>
<tr ng-repeat="a in arr">
   <td>{{a.acc.name}}</td>
   <td>{{a.acc.starting_balance}}</td>
   <td>{{a.inc.amount}}</td>
   <td>{{a.exp.amount}}</td>
</tr>

</table>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

听起来您正在尝试进行3次AJAX调用,然后将所有结果组合在一起。最好只在您调用的API中聚合此信息,而不是尝试修复此客户端。

但是如果你坚持使用API​​并且必须做这个客户端,我建议使用$q.all将3个单独的promises(来自API调用)组合成一个后处理函数。

例如,在您的控制器代码中:

$q.all([api.getAccount(), api.getExpense(), api.getIncome()])
    .then(combineInformation);

function combineInformation(apiResults) {
    var accountInfo = apiResults[0]; //result of getAccount()
    var expenseInfo = apiResults[1]; //result of getExpense()
    var incomeInfo = apiResults[2];  //result of getIncome()

    var aggregateInfo = accountInfo.map(buildInfo);

    function buildInfo(account) {
        var info = {
            id: account.id,
            account: account
        };

        info.expense = expenseInfo.find(function (e) { return e.id === info.id; });
        info.income = incomeInfo.find(function (i) { return i.id === info.id; });
        return info;
    }
    $scope.arr = aggregateInfo;
}

Demo on plunker