2016-04-02 47 views
0

我正在緩存$http數據使用angular-cache模塊。如果更新緩存數據,我想調用$http服務。問題我有這個代碼僅返回緩存數據,直到我不能自動清除緩存手動如何獲得角度js中更新的緩存數據

//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 
+0

請定義'是否更新緩存數據'是否意味着你更新本地信息或更新服務器上的數據。 –

+0

您應該使用[onExpire](https://github.com/jmdobry/angular-cache#onexpire)處理程序並再次獲取數據。 – fracz

回答

0

一號方法 - 使用$資源:

$資源將自動管理緩存你這麼有不需要強制緩存被清除。這個想法是,如果你有一個你可以查詢的資源,那麼這個查詢響應將被緩存,但是如果你爲同一個資源保存了某些內容,那麼以前緩存的數據必須是無效的,因此它會被清除。根據事件

第二個方法 - 強制高速緩存

有角將不知道數據被更新,某些情況下,你可能希望強制基於特定動作的更新。你可以通過調用remove方法來做到這一點。在你的情況下:

dataCache.remove(key);