2016-06-14 41 views
0

我在我的角度項目中使用插件ng-csv。我正在循環訪問一個數組,並調用$http get,它會爲我的csv文件返回一些信息。 我目前有它的1個結果工作見下文。

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; 

這將用一條記錄填充csv。然而,Im努力讓它與$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(); 

當調試queue這是充滿了保持$http數據諾言對象。同樣return $scope.output;保存所有結果。 ng-csv似乎沒有解釋它,我覺得我很接近。

任何幫助將不勝感激。

回答

1

更新您的那麼功能:

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

將返回每個請求的所有響應的陣列。

寫您的延遲是這樣的:

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

,並用它喜歡:

getData().then(function(data){ /*csv data is in data */ }) 
+0

感謝,在現在的反應填充了正確的數據意義的工作,使非常多的那。然而,返回$ q.defer();它在返回$ q.all之前返回csv。你知道我該如何解決這個問題嗎? – Antony

+1

我更新了我的答案 – Silvinus