Angular-cache未按预期工作

8

我尝试在我的项目中使用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
    };
});

在应用程序加载时,它会在控制台中打印“缓存不存在”的消息,并在本地存储中创建缓存。它在本地存储中创建了以下密钥-
“angular-cache.caches.CenterCache.keys” = [http://localhost/Services/Tracker/api/Center]

创建了另一个密钥

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

问题:

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

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


1
对于问题2:这不是问题,这就是它应该的工作方式。服务/工厂是单例,并且只会被创建一次。因此,在第一个导航到达并记录消息后,您将不会再次看到该消息,除非重新加载页面。 - CShark
1
根据您发布的代码,对于问题1,这是预期的行为,因为您声明的缓存是内存中的,所以如果您刷新页面,缓存将被清除。因此,当您发出请求时,第一次在缓存中找不到结果。请参见此工作示例。这是否符合您要做的事情,如果不是,请更清楚地说明哪些方面存在问题? - CShark
只有在同一页上对同一个API进行多次调用时,它才能正常工作。当您从一个页面导航到另一个页面时,它将无法正常工作(即无法从缓存中获取数据并调用API)。刷新页面后,它会再次下载数据。实际上,它应该从缓存中获取数据并显示“来自缓存”,就像Gmail一样。或者这可能是我的实现错误。 - sunder
问题2:如果数据已经缓存在本地存储中,但在从一个页面导航到另一个页面时,如果您的应用程序一遍又一遍地下载它,那么缓存有什么用处。以下是官方文档说明:注意:angular-cache不会自动从定义的存储系统中加载有关先前创建的缓存的元数据。这意味着在页面刷新时,此函数将返回未定义。要“重新加载”现有缓存,只需每次加载应用程序时使用相同名称重新创建缓存,缓存可能会加载以前保存在该缓存名称下的任何数据。 - sunder
当从缓存中获取数据时,它不会打印任何内容或发出任何声音。您将看不到在网络选项卡中发送的请求,因为它不需要。如果您说的是在网络选项卡中看到“From Cache”的情况,那是因为它正在从内置浏览器缓存中获取数据。该软件包与此分开。 - CShark
1
你能否提供一个例子,说明在页面之间导航时没有被缓存,因为我无法重现这个问题。 - CShark
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');
}]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接