【发布时间】:2014-05-01 22:24:21
【问题描述】:
我正在尝试学习 Angular,但我很难过。在我的工厂中,我正在使用这个 API 来收集所有回合数据,以便将其存储在一个对象中。由于有 20 轮,我宁愿只点击这个 API 一次,然后以某种方式缓存结果。如果我对特定回合进行单独调用并返回数据,我就可以正常工作,但是我想将每个链接中的任何数据共同添加到一个我可以从那里使用的大对象中。谢谢你的帮助。到目前为止,这是我的代码:
工厂:
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);
},
*/
};
}]);
控制器:
angular.module('dashCtrl', []).controller('dashController', function($scope, dashboard){
var allData = {};
$scope.allData = allData;
$scope.getData = function(){
dashboard.getRounds().then(function(data){
allData = data;
console.log(allData);
});
};
/* Below is what I have been doing invidually, but I don't want to call 20 functions!
dashboard.getRound1().success(function(data){
allData["round1"] = data.games[0];
console.log(allData);
});
dashboard.getRound2().success(function(data){
allData["round2"] = data.games[1];
console.log(allData);
});
*/
});
【问题讨论】:
-
嗯...一个问题是
i被声明在成功回调的范围之外。我假设您的对象返回时只有一个键:round20?为什么不能一次获得所有这些,而不是发出 20 个 AJAX 请求?
标签: javascript ajax angularjs object caching