Skip to content Skip to sidebar Skip to footer

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'

Solution 1:

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


}]);    

Solution 2:

First of all: like Carnaru Valentin said, you should create a service to wrap your $http calls.

Secondly, I don't get your $http.get('events') call. You don't pass any parameters to it (deviceID or whatnot).

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

Solution 3:

Thing is you reassign $scope.myObject to a new object before callback is fired and assigned events to the old one. So both callback's assign properties to same object. You could just put all of the code in callback.

Solution 4:

1. Create a service:

    functionDataService($http, appEndpoint){
        return {
            getLists: getData
        }

        functiongetData(){
            return$http.get(appEndpoint + 'lists')
        }
      }

2. Create controller:

functionListsController(DataService){
   varself = this;
   self.data = null;
   DataService.then(function(response){
       self.data = response.data;
   });

   // Here manipulate response -> self.data;
}

Post a Comment for "Angular.foreach Loop With $http.get"