【问题标题】:Get array Value after for loop completefor循环完成后获取数组值
【发布时间】:2015-07-07 00:15:54
【问题描述】:

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

端点 /team(今天的球队名单)

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

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

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

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

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

我有以下代码在这个plnkr 中工作,但我无法解决的是在我的 API 调用之后当我有$scope.team 时我是否可以依赖获取数据。当我对今天的数组进行 console.log 时,它会返回 []。有没有更好的方法来处理这种情况,例如在 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);
})();

【问题讨论】:

  • 您可以尝试使用 $q.all() 仅在所有承诺完成后更新您的目标数组。不是一对一。

标签: javascript json angularjs for-loop promise


【解决方案1】:

就像@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 2017-07-27
    • 2015-09-12
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    相关资源
    最近更新 更多