RestAngular 无法识别索引值

Index value is not recognized in RestAngular

当我在迭代中触发 rest API 调用时,索引值在块内无法识别。 参考代码片段:

$scope.user = [];
var userList = [{'id':1, 'name':'Joe'}, {'id':2, 'name': 'Jack'}];
for (var i=0; i<userList.length; i++) {
  Restangular.all('userInfo/userId' + userList[i].id).getList().then(function(users) {
    // returns given user information
    console.log(i);
    $scope.user.push({'id': userList[i].id, 'info': users});
  })
}

出现以下错误

Uncaught TypeError: Cannot read property 'i' of undefined 

如何解决?

试试这个。

This is called closure inside loop.

    $scope.user = [];
    var userList = [{'id':1, 'name':'Joe'}, {'id':2, 'name': 'Jack'}];
    for (var i=0; i<userList.length; i++) {
      function(index){
          Restangular.all('userInfo/userId/'+userList[index].id).getList().then(function(users) {
          // returns given user information
          console.log(index);
          $scope.user.push({'id': userList[index].id, 'info': users});
      })(i);
    }
}