[英]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.