2017-10-27 4 views
1

反復でAPI呼び出しを呼び出すと、ブロック内でインデックス値が認識されません。コードスニペットを参照してください :RestAngularでインデックス値が認識されない

$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 

をお持ちですか?

答えて

2

お試しください。

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); 
    } 
} 
関連する問題