2013-10-21 13 views
6

forループを使用して配列内の各オブジェクトのデータを更新し、すべてのデータを取得したら関数を実行する必要があります。私はfor each Ajax for Angularの適切な処理方法

$scope.units = ['u1', 'u2', 'u3']; 
    $scope.data = null; 
    //get individual unit data 
    $scope.getUnitData = function(unit){ 
     service.getUnitData(unit).success(function(response){ 
      $scope.data.push({'id' : response.id , 'value' : response.value}); 
     }); 
    }; 

    $scope.updateAllUnits = function(){ 
    $scope.data = null ; //remove existing data 
    angular.forEach($scope.units,function(val,key){ 
     $scope.getUnitData(val); 
    }; 
    console.log($scope.data); // Need to show all the data but currently it does not as the for each loop didn't complete 
    }; 

サービスは次のように定義され、この中にはjQueryをミックスし、私がやっているものですそれをここで

を行うための適切な角度の方法を行うにはしたくありません。

app.factory('service',function($http){ 
    return { 
     getUnitData : function(unit){ 
     return $http({ 
      url : myURL, 
      method : 'GET', 
      params : {'unit' : unit} 
      }); 
     } 

    } 

}); 

forループですべてのプルが完了したらコールバックを受け取るにはどうすればよいですか?

答えて

19

$http(...)コールの結果は約束です。これは、$q.allを使用して、それらの配列が完了するのを待つことを意味します。

$scope.updateAllUnits = function(){ 
    $scope.data = null ; //remove existing data 
    var promises = []; 
    angular.forEach($scope.units,function(val,key){ 
     promises.push($scope.getUnitData(val)); 
    }); 
    $q.all(promises).then(function success(data){ 
     console.log($scope.data); // Should all be here 
    }, function failure(err){ 
     // Can handle this is we want 
    }); 
}; 
+0

あなたのコードの 'promises'は単なる配列です。 $ qは、この配列にすべてのオブジェクトがあることをどのように知っていますか? – lostpacket

+1

我々は 'forEach'の内部でそれを同期させることを約束しています。 '$ q.when'を呼び出すと、約束が作成されますが解決されません(サーバからのデータはまだあります)。 '$ q.when'はこれがすべて完了するのを待ちます。私は '$ http'がすでに約束を返すと認識したので、この答えの大きな部分を削除しました。 – Andyrooger

+0

'$ q.when'は約束事を取ることができますか?もしそうなら、良い答えです! –

関連する問題