与$ http.get的angular.forEach循环 [英] angular.forEach loop with $http.get
问题描述
我想创建一个包含一些对象的数组
I want to create an array containing some objects
首先,我从服务器中获得第一个数组,其中包含诸如此类的设备列表
Firstly, I get a first array from the server containing a list of devices like this
[
{accountID : "sysadmin",deviceID : "123"},
{accountID : "sysadmin",deviceID : "3"}
...
]
然后我创建一个包含一些对象的第二个数组,每个对象代表一个设备(设备ID),并包含我从服务器获取的该设备的事件数组
Then I create a second array containing some objects that each object represent a device(deviceID) and contains an array of events of this device that I get from the server
我对第一个数组进行如下循环:
I do a loop upon the first array like this :
$scope.myArrayofDevices = [];
angular.forEach(response, function(device){
$scope.myObject={};
$scope.myObject.device = device.deviceID;
$http.get('events')
.success(function (data) {
$scope.myObject.events = data;
});
$scope.myArrayofDevices.push($scope.myObject);
});//end for loop
我正确地从服务器获取了事件数据.
I get events data from the server correctly .
但是,当我检查 $ scope.myArrayofDevices
数组时,我得到的第一个对象只有deviceID且没有事件数组,而第二个对象只有deviceID和events数组正确
But, when I check $scope.myArrayofDevices
array I get an the first object with only the deviceID and no event array and the second object with deviceID and events array correctly
像这样:
[
{deviceID : 123, events:},
{deviceID : 3 , events : array[5]}
]
我该如何解决这个问题?
How can I solve this issue ?
请注意,我尝试将数组分配给 $ scope.myObject.events
,它的工作原理非常完美,问题是使用带有$ http的循环
Note that I try to assign an array to $scope.myObject.events
it works perfectly the problem is using a loop with $http
推荐答案
您可以使用 $ q.all()
解析承诺数组并获得最终结果
You can use $q.all()
to resolve an array of promises and get the final result
angular.module('app', []);
angular.module('app').controller('ExampleController', ['$scope', '$q', function($scope, $q) {
$scope.myArrayofDevices = [];
$scope.getDeviceObject = function(deviceId) {
return $http.get('events/' + deviceId).then(function(deviceEvents) {
return {
"device": deviceId,
"events": deviceEvents
};
});
}
var promises = [];
angular.forEach(response, function(device) {
promises.push($scope.getDeviceObject(device.deviceID));
});
/*
* Combines multiple promises into a single promise
* that will be resolved when all of the input promises are resolved
*/
$q.all(promises).then(function(devices) {
$scope.myArrayofDevices = $scope.myArrayofDevices.concat(devices);
});
}]);
这篇关于与$ http.get的angular.forEach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!