angular.for每个循环与$http.get



我想创建一个包含一些对象的数组

首先,我从服务器获得第一个数组,其中包含这样的设备列表

 [ 
{accountID : "sysadmin",deviceID : "123"},
{accountID : "sysadmin",deviceID : "3"}
    ...
    ]

然后我创建第二个数组,其中包含一些对象,每个对象代表一个设备(deviceID(,并包含我从服务器获取的该设备的事件数组

我在第一个数组上做一个循环,如下所示:

$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我得到一个只有设备ID而没有事件数组的第一个对象,以及第二个具有设备ID和事件数组的对象正确

喜欢这个:

[
{deviceID : 123, events:},
{deviceID : 3 , events : array[5]}
]

我该如何解决这个问题?

请注意,我尝试分配一个数组,$scope.myObject.events它工作正常,问题是使用带有$http的循环

您可以使用$q.all()来解决一系列承诺并获得最终结果

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')电话。您不会向其传递任何参数(设备ID或其他参数(。

它是否返回每个设备的所有事件列表?对于特定设备 ?

如果您只是忘记向查询添加参数:这是一个可行的解决方案:

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重新分配给新对象。因此,两个回调都将属性分配给同一对象。您可以将所有代码放在回调中。

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;
}

最新更新