简体   繁体   English

$ 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"}
    ...
    ]

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 然后,我创建第二个数组,其中包含一些对象,每个对象代表一个设备(设备ID),并包含从服务器获取的该设备的事件数组

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 . 我可以从服务器正确获取事件数据。

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 但是,当我检查$scope.myArrayofDevices数组时,我得到了第一个对象,该对象仅具有deviceID并且没有事件数组,而第二个对象具有deviceID和events数组正确

like this : 像这样 :

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

How can I solve this issue ? 我该如何解决这个问题?

Note that I try to assign an array to $scope.myObject.events it works perfectly the problem is using a loop with $http 请注意,我尝试为$scope.myObject.events分配一个数组,它工作正常,问题是使用带有$ http的循环

You can use $q.all() to resolve an array of promises and get the final result 您可以使用$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);
    });


}]);    

First of all: like Carnaru Valentin said, you should create a service to wrap your $http calls. 首先:就像Carnaru Valentin所说的那样,您应该创建一个服务来包装$http调用。

Secondly, I don't get your $http.get('events') call. 其次,我没有$http.get('events')您的$http.get('events')电话。 You don't pass any parameters to it (deviceID or whatnot). 您不向其传递任何参数(deviceID或诸如此类)。

Does it return a list of all events for every devices ? 它是否返回每个设备的所有事件的列表? For a specific device ? 对于特定设备?

If you just forgot to add a parameter to the query: here is a solution that could work: 如果您只是忘记向查询添加参数,则可以使用以下解决方案:

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

Thing is you reassign $scope.myObject to a new object before callback is fired and assigned events to the old one. 问题是在触发回调并将事件分配给旧对象之前,将$scope.myObject重新分配给一个新对象。 So both callback's assign properties to same object. 因此,两个回调的assign属性都分配给同一对象。 You could just put all of the code in callback. 您可以将所有代码放在回调中。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM