[英]angular manage data of multiple http calls
在這種情況下,我有一個嚴重的問題。 我通過下面的代碼從github API獲取數據,但是由於github每頁僅允許30個結果,因此我想獲取所有數據以獲得更好的排序選項並將其推送到一個對象數組。 下面找到一個可以正常工作的代碼
$scope.getData = function () {
$http({
method: "GET",
url: api url + pageNum
}).then(function mySucces(response) {
$scope.mydata = response.data;
$scope.isLoading = false;
$scope.result = $scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; });
}, function myError(response) {
$scope.error = response.statusText;
});
};
但是我想做這樣的事情
$scope.getData = function () {
for(var i =0; i<= $scope.pages.length; i++){
$http({
method: "GET",
url: "apiUrl + i
}).then(function mySucces(response) {
$scope.mydata = response.data;
$scope.isLoading = false;
$scope.result = $scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; });
}, function myError(response) {
$scope.error = response.statusText;
});
};
有什么想法要這樣做嗎?
您應該在AngularJS網站上查看$ q文檔 。
$scope.getData = function () {
$scope.result = [];
$scope.error = [];
$q.all($scope.pages.map(function(page) {
return $http({
method: "GET",
url: "apiUrl" + i
})
// This function will be triggered when each call is finished.
.then(function mySucces(response) {
$scope.mydata.push(response.data);
$scope.result.push($scope.mydata.map(function (a) { return { 'name': a.name, 'html_url': a.html_url }; }));
})
}))
// This call will be called when all of the calls are finished.
.then(function(success) {
$scope.isLoading = false;
}).catch(function (error) {
$scope.error = response.statusText;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.