Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - 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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


}]);    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...