angular-cache无法按预期工作

sun*_*der 8 caching local-storage angularjs angular-cache angular-local-storage

我试图将angular-cache模块用于我的项目,但不确定它是否正常工作.以下是代码 -

angular.module('TrackerApp').factory('TrackerFactory', function ($resource, CacheFactory) {
    if (!CacheFactory.get('CenterCache')) {
        console.log('cache does not exists');
        CacheFactory.createCache('CenterCache', {
            maxAge: 5 * 60 * 1000,
            deleteOnExpire: 'aggressive'
        });
    }
    var centerCache = CacheFactory.get('CenterCache');
    var CenterClass = $resource(_ServiceBaseURL + 'api/Center/:id',{},{
        query: {
            method: 'GET',
            cache: centerCache,
            isArray:true
        }
    });
    CenterClass.GetMultipleAsObject = function () { return this.query(); };
    return {
        CenterClass: CenterClass
    };
});
Run Code Online (Sandbox Code Playgroud)

在加载应用程序时,它会在控制台中打印"缓存不存在"的消息,它会在本地存储中创建缓存.它创建了本地存储的关键 -

“angular-cache.caches.CenterCache.keys” = [http://localhost/Services/Tracker/api/Center]
Run Code Online (Sandbox Code Playgroud)

另一个关键是创建

“angular-cache.caches.CenterCache.data.http:// localhost/Services/Tracker/api/Center” = mystoredvalue
Run Code Online (Sandbox Code Playgroud)

问题 -

  1. 在页面刷新(f5),我确实看到再次打印控制台消息,在http调用中,我可以看到"中心"信息正在下载,它不是从缓存中选取的.
  2. 在从一个页面导航到另一个页面时,我看不到控制台消息被打印.但我确实看到"中心"api被调用.数据正在网络选项卡中下载.它应该从缓存中选择.

我觉得它不是从缓存中挑选数据.我错过了什么吗?

小智 1

也许你选择使用这种结构;

angular.module('cacheApp', []).
controller('CacheCtrl', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  $scope.keys = [];
  // get cacheFactory
  $scope.cache = $cacheFactory('CenterCache');
  // Custom put
  // call function key and value
  $scope.put = function(key, value) {

  // Control cache
    if (angular.isUndefined($scope.cache.get(key))) {
      $scope.keys.push(key);
    }

   // Fill cache
    $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  };
}]);
Run Code Online (Sandbox Code Playgroud)

如果你想使用 cookieStore

angular.module('cookieStoreExample', ['ngCookies'])
.controller('ExampleController', ['$cookieStore', function($cookieStore) {

  // Fill cookie
  $cookieStore.put('CenterCache', yourObject );


  // Get cookie
  var favoriteCookie = $cookieStore.get('CenterCache');

  //If you want
  // Removing a cookie
  $cookieStore.remove('CenterCache');
}]);
Run Code Online (Sandbox Code Playgroud)