AngularJS $http サービスの場合、
シーケンシャル データにアクセスするために $http 呼び出しをループするにはどうすればよいですか?ただし、各呼び出しでは、次の呼び出しで前の戻りデータを使用する必要があります。
前の呼び出しからの戻りデータを必要とする連続した $http 要求を作成したいと考えています。Instagram API からすべてのフォロワーを取得しようとしています。サーバーは、返されるデータを制限し、フェッチするデータがさらにある場合に別の呼び出しを行うためのオフセットを提供します。明確でない場合は、 http://instagram.com/developer/endpoints/のページネーションの見出しを確認してください。
私の解決策はうまくいきますが、それは醜く、安全ではなく、もっと良い方法が必要だと思います。私がしていることは、$http を実行する関数を再帰的に呼び出し、関数自体を渡し、必要に応じてプロミスで実行することです。
だから、私の質問は: 約束の中で再帰的に呼び出すことなくこれを行う別の方法はありますか?
これは私の最初のスタックオーバーフローの投稿なので、私の考えの整理がいかに不十分であるかをお詫びします...
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');
});
};
}]);