[英]angular.forEach loop with $http.get
我想创建一个包含一些对象的数组
首先,我从服务器中获得第一个数组,其中包含这样的设备列表
[
{accountID : "sysadmin",deviceID : "123"},
{accountID : "sysadmin",deviceID : "3"}
...
]
然后,我创建第二个数组,其中包含一些对象,每个对象代表一个设备(设备ID),并包含从服务器获取的该设备的事件数组
我对第一个数组执行如下循环:
$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
我可以从服务器正确获取事件数据。
但是,当我检查$scope.myArrayofDevices
数组时,我得到了第一个对象,该对象仅具有deviceID并且没有事件数组,而第二个对象具有deviceID和events数组正确
像这样 :
[
{deviceID : 123, events:},
{deviceID : 3 , events : array[5]}
]
我该如何解决这个问题?
请注意,我尝试为$scope.myObject.events
分配一个数组,它工作正常,问题是使用带有$ http的循环
您可以使用$q.all()
来解析一个promise数组并获得最终结果
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);
});
}]);
首先:就像Carnaru Valentin所说的那样,您应该创建一个服务来包装$http
调用。
其次,我没有$http.get('events')
您的$http.get('events')
电话。 您不向其传递任何参数(deviceID或诸如此类)。
它是否返回每个设备的所有事件的列表? 对于特定设备?
如果您只是忘记向查询添加参数,则可以使用以下解决方案:
var promises = response.map(function (device) {
return $http.get('events/' + device.deviceID)
.then(function (data) {
return {
device: device.deviceID,
events: data
};
});
})
$q.all(promises)
.then(function (devices) {
$scope.myArrayofDevices = $scope.myArrayofDevices.concat(devices);
// alternatively: $scope.myArrayofDevices = devices;
});
问题是在触发回调并将事件分配给旧对象之前,将$scope.myObject
重新分配给一个新对象。 因此,两个回调的assign属性都分配给同一对象。 您可以将所有代码放在回调中。
1. Create a service:
function DataService($http, appEndpoint){
return {
getLists: getData
}
function getData(){
return $http.get(appEndpoint + 'lists')
}
}
2. Create controller:
function ListsController(DataService){
var self = this;
self.data = null;
DataService.then(function(response){
self.data = response.data;
});
// Here manipulate response -> self.data;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.