Javascript 迭代Ajax调用并将所有数据存储在angularjs中的object中
我正在努力学习,但我被难倒了。在我的工厂里,我使用这个API来收集所有轮次数据,以便将其存储在一个对象中。因为有20轮,我更喜欢只点击这个API一次,然后以某种方式缓存结果。如果我对特定的一轮进行单独调用并返回数据,我就可以使用它,但我希望将每个链接中的任何数据一起添加到一个大对象中,从那时起我就可以使用它。谢谢你的帮助。以下是我目前的代码: 工厂:Javascript 迭代Ajax调用并将所有数据存储在angularjs中的object中,javascript,ajax,angularjs,object,caching,Javascript,Ajax,Angularjs,Object,Caching,我正在努力学习,但我被难倒了。在我的工厂里,我使用这个API来收集所有轮次数据,以便将其存储在一个对象中。因为有20轮,我更喜欢只点击这个API一次,然后以某种方式缓存结果。如果我对特定的一轮进行单独调用并返回数据,我就可以使用它,但我希望将每个链接中的任何数据一起添加到一个大对象中,从那时起我就可以使用它。谢谢你的帮助。以下是我目前的代码: 工厂: angular.module('dashFactory', []).factory('dashboard', ['$http', function
angular.module('dashFactory', []).factory('dashboard', ['$http', function($http) {
var allRounds = {};
return {
getRounds: function() {
for (var i=1; i<21; i++){
var url = 'http://footballdb.herokuapp.com/api/v1/event/world.2014/round/' + i + '?callback=JSON_CALLBACK';
$http.jsonp(url).then(function(result){
allRounds["round" + i] = result;
});
}
return allRounds;
}
/* Below works BUT I have to call each function individually in controller
//getRound1: function() {
var url = 'http://footballdb.herokuapp.com/api/v1/event/world.2014/round/1?callback=JSON_CALLBACK';
return $http.jsonp(url);
},
getRound2: function() {
var url = 'http://footballdb.herokuapp.com/api/v1/event/world.2014/round/2?callback=JSON_CALLBACK';
return $http.jsonp(url);
},
*/
};
}]);
首先,提出一个请求以获得全部20个。你没有理由提出20个请求。我喜欢使用的缓存策略如下:
app = angular.module('app', [])
.service('Round', function($log, $q, $http) {
var rounds;
var deferred = $q.defer();
return {
getRounds: function(fromServer) {
if(rounds && !fromServer) {
deferred.resolve(rounds);
} else {
$http.get('http://footballdb.herokuapp.com/api/v1/event/world.2014/rounds')
.success(function(results) {
rounds = results;
deferred.resolve(rounds);
})
.error(function(error) {
$log.error('Could not get rounds: ' + error);
deferred.reject(error);
});
}
return deferred.promise;
}
};
})
定义与此类似的控制器:
app.controller('ACtrl', function($scope, Round) {
Round.getRounds().then(function(rounds) {
$scope.rounds = rounds;
});
})
app.controller('BCtrl', function($scope, Round) {
Round.getRounds().then(function(rounds) {
$scope.rounds = rounds;
});
});
本例仅对应用程序的运行时发出一个AJAX请求(当然,除非有人刷新页面)。所有控制器中可用的
对象与服务中的对象相同。对其进行修改将在其他控制器中更改它。或者,通过调用getRounds(true)
再次从服务器请求查房。因为承诺也在控制器/指令之间共享,所以每次从服务器请求轮次时,所有轮次都将在控制器中刷新。好吧。。。一个问题是,i
被声明在成功回调的范围之外。我假设对象返回时只有一个键:round20
?为什么你不能一次获得所有这些,而不是发出20个AJAX请求?
app.controller('ACtrl', function($scope, Round) {
Round.getRounds().then(function(rounds) {
$scope.rounds = rounds;
});
})
app.controller('BCtrl', function($scope, Round) {
Round.getRounds().then(function(rounds) {
$scope.rounds = rounds;
});
});