8

我试图在我的项目中使用angular-cache模块,但不确定它是否正常工作。下面是代码——</p>

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

在加载应用程序时,它会在控制台中打印“缓存不存在”的消息,并且会在本地存储中创建缓存。它在本地存储中创建以下键-

“angular-cache.caches.CenterCache.keys” = [http://localhost/Services/Tracker/api/Center]

另一个密钥被创建

“angular-cache.caches.CenterCache.data.http:// localhost/Services/Tracker/api/Center” = mystoredvalue

问题——</p>

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

我觉得它没有从缓存中提取数据。我错过了什么吗?

4

1 回答 1

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

如果你想使用 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');
}]);
于 2017-08-12T23:15:10.157 回答