javascript - angular.forEach loop with $http.get -


i want create array containing objects

firstly, first array server containing list of devices

 [  {accountid : "sysadmin",deviceid : "123"}, {accountid : "sysadmin",deviceid : "3"}     ...     ] 

then create second array containing objects each object represent device(deviceid) , contains array of events of device server

i loop upon first array :

$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 loop  

i events data server correctly .

but, when check $scope.myarrayofdevices array first object deviceid , no event array , second object deviceid , events array correctly

like :

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

how can solve issue ?

note try assign array $scope.myobject.events works problem using loop $http

you can use $q.all() resolve array of promises , 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 single promise      * resolved when of input promises resolved      */     $q.all(promises).then(function(devices) {         $scope.myarrayofdevices = $scope.myarrayofdevices.concat(devices);     });   }]);     

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -