0

我正在$http使用angular-cache模块缓存数据。$http如果缓存数据更新,我想调用服务。问题我有这个代码只返回缓存的数据,直到我没有手动清除缓存

//controller.js   
angular.module('adminPanelApp').controller('recordController',recordController);

    function recordController($scope,userService) {
      $scope.title='FeedBacks From Users';  //This is Title to be sset to page
      var promise = userService.getRecord(1);
      promise.then(function (response) {
        $scope.users = response;
      });
    }

    //service.js

    angular.module('adminPanelApp').service('userService', ['$http', '$q','CacheFactory', function ($http, $q,CacheFactory) {
      CacheFactory('dataCache', {
        cacheFlushInterval: 60, // This cache will clear itself every hour
        deleteOnExpire: 'aggressive', // Items will be deleted from this cache when they expire
        storageMode:'localStorage'
      });

      return {
        getRecord: function (id) {
          var deferred = $q.defer();
          var start = new Date().getTime();
          var dataCache = CacheFactory.get('dataCache');
          if (dataCache.get(id)) {
            deferred.resolve(dataCache.get(id));
          } else {
            $http.get('http://54.86.64.100:3000/api/v1/user/feedback-all', +id).success(function (data) {
              dataCache.put(id, data);
              console.log('time taken for request: ' + (new Date().getTime() - start) + 'ms');
              deferred.resolve(data);
              dataCache.get(id, data);
            });
          }
          return deferred.promise;
        }};//
    }]);//end of service
4

1 回答 1

0

第一种方法 - 自动,使用 $resource:

$resource 将自动为您管理缓存,因此无需强制清除缓存。这个想法是,如果您有可以查询的资源,则该查询响应将被缓存,但如果您为同一资源保存某些内容,则先前缓存的数据必须是无效的,因此会为您清除。

第二种方法-基于事件的强制缓存

在某些情况下,Angular 不知道数据正在更新,您可能希望根据特定操作强制更新。您可以通过调用 remove 方法来做到这一点。在你的情况下:

dataCache.remove(key);
于 2016-04-02T06:12:00.827 回答