0

When I fire an rest API call in an iteration then index value is not recognized inside the block. Refer code snippet:

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

Got the following error

Uncaught TypeError: Cannot read property 'i' of undefined 

How to resolve this?

Pez
  • 1,091
  • 2
  • 14
  • 34

1 Answers1

2

Try This.

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);
    }
}
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48