for循环完成后获取数组值

时间:2015-07-07 00:15:54

标签: javascript json angularjs for-loop promise

我正在处理一个数据集,我想在某一天获得工作人员的姓名和职位。
问题是数据在三个不同的端点中分离,所以我需要将它们全部连接起来以获取我所追求的有意义的数据。

端点 /团队(今天团队参加)

[{
  "employeeID": "111"
},
{
  "employeeID": "333"
},
{
  "employeeID": "444"
}]

/ staff /:employeeID(plnkr中的name-staffID.json)

{
  "employeeID": "111",
  "firstName": "Tom",
  "lastName":"Smith"
}

/ role /:employeeID(plnkr中的role-staffID.json)

{
  "roleID": "1",
  "employeeID": "111",
  "role": "Manager"
}

我在下面的plnkr中使用了以下代码,但我无法解决的问题是,在API调用后{em} $scope.team时,是否可以依赖获取数据。当我在console.log中使用[]时,它返回了数组todaysTeam。是否有更好的方法来处理这种情况,例如在forloop完成集合$scope.team之后,或者我已经采用可靠的方法。

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
    <script src="script1.js"></script>
  </head>

  <body>
    <div ng-app="App">
      <div ng-controller="MainCtrl">
        <ul>
          <li ng-repeat="t in team">{{t.firstname}} is the {{t.role}}</li>
        </ul>
    </div>
  </body>

</html>

JS:

(function () {
    function MainCtrl($scope, APIService) {
        function getTeams() {
          var todaysTeam = [];
            APIService.getTeam()
            .success(function (data) {
              for (var i in data) {
              //console.log(data[i].employeeID);
                APIService.getStaff(data[i].employeeID)
                .success(function (staff) {
                  APIService.getRole(staff.employeeID)
                  .success(function (role) {
                    console.log(staff.firstName + ' is the ' + role.role);
                    todaysTeam.push({
                      "firstname": staff.firstName,
                      "role": role.role
                    });
                    console.log(todaysTeam);
                  });
                });
              }
            });
            console.log(todaysTeam);
            $scope.team = todaysTeam;
        }
      getTeams();
    }      
    function APIService($http) {
        var APICalls = {};
        APICalls.getTeam = function () {
            return $http.get('team.json')
            .success(function (data, status, headers, config) {})
            .error(function (data, status, headers, config) {});
        };
        APICalls.getStaff = function (staffID) {
            return $http.get('name-' + staffID + '.json')
            .success(function (data, status, headers, config) {})
            .error(function (data, status, headers, config) {});
        };
        APICalls.getRole = function (staffID) {
            return $http.get('role-' + staffID + '.json')
            .success(function (data, status, headers, config) {})
            .error(function (data, status, headers, config) {});
        };        
        return APICalls;
    }
    angular.module('App', [])
        .controller('MainCtrl', MainCtrl)
        .factory('APIService', APIService);
})();

1 个答案:

答案 0 :(得分:3)

像@JoaozitoPolo一样说,你需要的是$q.all

function MainCtrl($scope, $q, APIService) {
  function getTeams() {
    var tmpTeamData = {}, promises = [];

    APIService.getTeam().then(function(teamData){
      teamData.forEach(function(datum){
        tmpTeamData[datum.employeeID] = datum;
        var pGetStaff = APIService.getStaff(datum.employeeID).then(addDatum);
        var pGetRole = APIService.getRole(datum.employeeID).then(addDatum);
        promises.push(pGetStaff);
        promises.push(pGetRole);
      });
      $q.all(promises).then(function(){
        //changing structure from object to array
        $scope.team = [];
        for(var key in tmpTeamData) $scope.team.push(tmpTeamData[key]);
      });
    });

    function addDatum(datum){
      if(!tmpTeamData[datum.employeeID]){
        tmpTeamData[datum.employeeID] = datum;
      }else{
        for(var key in datum)   tmpTeamData[datum.employeeID][key] = datum[key];
      }
    }
  }
  getTeams();      
}

plnkr demo