I am caching $http data using angular-cache module. I want to call $http service if cached data is updated. Problem I am having that this code is returning only cached data till I am not clearing cache manually
//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
1st method- Automatically, using $resource:
$resource will manage the cache for you automatically so there's no need to force the cache to be cleared. The idea is that if you have a resource that you can query, that query response will be cached, but if you save something for that same resource, the previously cached data must be invalid, so it is cleared for you.
2nd method- force cache based upon an event
There are certain cases angular won't know that the data is being updated and you may want to force an update based on a specific action. You can do this by calling the remove method. In your case: