在AngularJS的工厂中实现缓存

在AngularJS的工厂中实现缓存,angularjs,caching,repository-pattern,cachefactory,Angularjs,Caching,Repository Pattern,Cachefactory,我目前正在尝试在angular应用程序中实现缓存服务,以减少端点上的工作负载,并(希望)在我的界面上看到一些轻微的、可能可以忽略不计的加载时间 我首先实现了自己的cacheService,它几乎是$cacheFactory (function () { 'use strict'; angular .module('app') .factory('cacheService', cacheService); cacheService.$in

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

我首先实现了自己的
cacheService
,它几乎是
$cacheFactory

(function () {
    'use strict';

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

    cacheService.$inject = ['$cacheFactory']

    function cacheService($cache) {
        return $cache('appCache');
    }
})();
然后我有了
datacontext
,它本质上是一个工作单元,它使用我的
cacheService
$http
(我还有几个其他的“存储库”,但只展示了我正试图使用的存储库)

然后是我的角度控制器,它使用
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
语句,这意味着
规则
是未定义的,所以它从不使用缓存,它只会再次调用我的API,获取数据,缓存数据(该部分工作正常,我在将其放入缓存后直接从缓存中拉出,对其进行了测试),然后返回承诺。一次又一次


有人能指出我不理解这应该如何工作的地方吗?

鉴于angular中的所有工厂都是单例的,基本的缓存工厂实现应该是这样的

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  } 
})

这应该是可行的,除非您想在硬刷新时维护缓存。

这似乎是一个不错的解决方案,但更多的是一种解决方法,而不是对我的问题的回答。
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  } 
})