对于 AngularJS $http 服务,
如何循环 $http 调用以访问顺序数据,而每次调用都需要在下一次调用中使用先前的返回数据?
我想发出连续的 $http 请求,这些请求需要从上一次调用中返回数据。我正在尝试从 Instagram API 获取所有关注者。服务器限制返回数据并提供偏移量,以便在要获取更多数据时进行另一次调用。如果不清楚,请查看http://instagram.com/developer/endpoints/上的分页标题。
我的解决方案有效,但我认为它丑陋、不安全,必须有更好的方法。我所做的是递归调用一个执行 $http 的函数,传入函数本身并在需要时在 Promise 中执行它。
所以,我的问题是:是否有另一种方法可以做到这一点,而无需在承诺中递归调用?
这是我的第一篇 stackoverflow 帖子,所以我为我的想法组织得很差表示歉意......
var app = angular.module('instagramApp', ['ngRoute']);
app.controller('FollowsCtrl', ['$scope', 'Instagram', '$http', function($scope, Instagram, $http){
$scope.follows = [];
$scope.follows_count = 0;
loadFollows();
function loadFollows(){
Instagram.getFollows().then(function(users){
$scope.follows = users;
$scope.follows_count = users.length;
});
}
}]);
//Communicates with Server
app.service('Instagram', ['$http', function($http){
//Return public API.
return ({
getFollows: getFollows
});
//Public method
function getFollows(){
return _getFollows(_getFollows, '', []);
}
//Recursive private method
function _getFollows(callback_fn, cursor, users){
var base = 'https://api.instagram.com/v1/users/12345678910/follows';
var access_token = '?access_token=PUT_ACCESS_TOKEN_HERE=JSON_CALLBACK';
var url = base + access_token + cursor;
return $http.jsonp(url).then(
//success
function(result){
//add follow users from server to array
users = users.concat(result.data.data);
//check if more data needs to be retrieved from the server
if(result.data.pagination.next_cursor)
{
cursor = '&cursor=' + result.data.pagination.next_cursor;
//TODO: call again if more data to retrieve
return callback_fn(callback_fn, cursor, users);
}
//all data fetched, return it
else
{
return users;
}
},
//error
function(result){
console.log('error');
});
};
}]);