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ループですべてのプルが完了したらコールバックを受け取るにはどうすればよいですか?
あなたのコードの 'promises'は単なる配列です。 $ qは、この配列にすべてのオブジェクトがあることをどのように知っていますか? – lostpacket
我々は 'forEach'の内部でそれを同期させることを約束しています。 '$ q.when'を呼び出すと、約束が作成されますが解決されません(サーバからのデータはまだあります)。 '$ q.when'はこれがすべて完了するのを待ちます。私は '$ http'がすでに約束を返すと認識したので、この答えの大きな部分を削除しました。 – Andyrooger
'$ q.when'は約束事を取ることができますか?もしそうなら、良い答えです! –