问题描述:

I'm using the plug in ng-csv for my angular project. I'm looping through an array and calling a $http get which returns some information for my csv file.

I currently have it working for 1 result see below.

var deferred = $q.defer();

$http({

method: 'get',

url: "[endpoint]user/212121"

}).success(function(data, status, headers, config) {

var ur = data;

deferred.resolve([{a:ur.accountId, b:ur.firstName, c:ur.email}]);

})

return deferred.promise;

This will populate the csv with the one record. However Im struggling to get it to work with $q.all.

var queue=[];

$scope.testing.forEach(function(userjson){

queue.push($http({

method: 'get',

url: "[endpoint]"+userjson.userId

}).then(function(response) {

var ur = response.data;

$scope.output.push({a:ur.accountId, b:ur.firstName, c:ur.email});

}));

})

$q.all(queue).then(function(response) {

return $scope.output;

});

return $q.defer();

When I debug queue it is full of promise objects that hold the $http data. Likewise return $scope.output; holds all the results. ng-csv doesn't seem to interpret it, I feel I'm close.

Any help would be much appreciated.

网友答案:

Update your then functions :

$http({
        method: 'get',
        url: "[endpoint]"+userjson.userId                                               
     }).then(function(response) {
         return {a:response.accountId, b:response.firstName, c:response.email};
        })

and :

$q.all(queue).then(function(response) {
   return response;
});

will be return an array of all response for each request.

Write your defer like this :

function getData() {
var queue=[];
var defered = $q.defer();
$scope.testing.forEach(function(userjson){
  queue.push($http({
        method: 'get',
        url: "[endpoint]"+userjson.userId                                               
     }).then(function(response) {
         return {a:response.accountId, b:response.firstName, c:response.email};
        }));
})

$q.all(queue).then(function(response) {
  return defered.resolve(response);
});
return defered.promise;
}

and use it like :

getData().then(function(data){ /*csv data is in data */ })
相关阅读:
Top