迭代Ajax调用并将所有数据存储在angularjs中的对象中

时间:2014-05-01 22:24:21

标签: javascript ajax angularjs object caching

我试图学习角度,我很难过。在我的工厂,我正在使用此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);
});
*/

});

1 个答案:

答案 0 :(得分:0)

首先,提出一个要求获得所有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请求(除非有人刷新页面)。所有控制器中可用的rounds对象与服务中的对象相同。对其进行修改将在其他控制器中更改它。 (可选)通过调用getRounds(true)再次从服务器请求回合。因为promise也是在控制器/指令之间共享的,所以每次从服务器请求轮次时,所有轮次都将在控制器中刷新。

相关问题