在AngularJS中的工厂中实现缓存

时间:2014-11-04 16:11:53

标签: angularjs caching repository-pattern cachefactory

我目前正在尝试在我的角度应用程序中实现缓存服务,以减少端点上的工作量,并且(希望)在我的界面上看到一些轻微的,可能忽略不计的加载时间。

我已经开始实施自己的cacheService,它几​​乎是$cacheFactory

的包装器
(function () {
    'use strict';

    angular
        .module('app')
        .factory('cacheService', cacheService);

    cacheService.$inject = ['$cacheFactory']

    function cacheService($cache) {
        return $cache('appCache');
    }
})();

然后我datacontext基本上是一个消耗我的cacheService$http的工作单元(我还有其他几个"存储库"在那里但只显示我尝试与之合作的那个人)

(function () {
    'use strict';

    angular
        .module('app')
        .factory('datacontext', datacontext);

    datacontext.$inject = ['$http', 'cacheService', '$q'];

    function datacontext($http, cache, $q) {    
        var rulesRepo = (function () {
            var repo = {
                get: getRule,
                getAll: getAll
            };

            return repo;

            function getRule(ruleId) {
                // placeholder
            }

            function getAll() {
                var deferred = $q.defer();

                // check to see if we have data cached
                var rules = cache.get('rules');
                if (rules) { // if it's cached, return it
                    deferred.resolve(rules);
                } else { // otherwise get the data from the API, cache it and return it
                    $http.get('/api/rules')
                        .then(function (response) {
                            cache.put('rules', response.data);
                            deferred.resolve(response.data);                            
                        });
                }
                return deferred.promise;
            }
        })();    

        var service = {
            rules: rulesRepo
        };

        return service;
    }
})();

然后我的角度控制器消耗datacontext

(function () {
    'use strict';

    angular
        .module('app')
        .controller('HomeController', HomeController);

    HomeController.$inject = ['$scope', 'datacontext'];

    function HomeController($scope, context) {    
        context.rules.getAll()
            .then(
                function (data) { // success
                    $scope.rules = data;
                },
                function (response) { // failure
                    console.log(response);
                });

        activate();
        function activate() { }
    }
})();

我目前面临的问题是,每当我拨打context.rules.getAll()时,它始终会点击else语句,意味着rules未定义,所以它永远不会使用缓存,它只是再次调用我的API,获取数据,缓存它(该部分工作我已经通过在缓存后将其从缓存中拉出来测试它),然后返回promise。一遍又一遍。

有人可以指出我不知道这应该如何运作吗?

1 个答案:

答案 0 :(得分:0)

鉴于角中的所有工厂都是单件,基本的缓存工厂实现将是这样的

app.factory(cacheFactory, function(){
  var localCache = {};
  var put  = function(key, value)     { localCache[key] = value;    }
  var get  = function(key)     { return localCache[key];    }
  return { get:get, put:put  } 
})

这应该可行,除非你想在硬刷新时保持缓存。