jmdobry / angular-cache

angular-cache is a very useful replacement for the Angular 1 $cacheFactory.
http://jmdobry.github.io/angular-cache
MIT License
1.39k stars 156 forks source link

Getting undefined while retrieving cached data on page refresh #249

Closed shailv closed 7 years ago

shailv commented 8 years ago

Hi, I am having the same problem as #175 . When I refresh the page, the cached data gets wiped out and I get an undefined when I try to get the cache value. I am storing in localStorage. Here's my code:

app.factory('LogInService', ['$http', '$q', 'CacheFactory', function($http, $q, CacheFactory){

        var userData = {'firstName': '','lastName': ''};
    var userCache = {};
    var cacheOptions = CacheFactory('userDataCache', {
        maxAge: 15 * 60 * 1000, // Items added to this cache expire after 15 minutes.
        cacheFlushInterval: 60 * 60 * 1000, // This cache will clear itself every hour.
        deleteOnExpire: 'aggressive', // Items will be deleted from this cache right when they expire.
        storageMode: 'localStorage' // This cache will use `localStorage`.
    });

return{
        //save to cache
        saveUserData: function (userInfo){
            var deferred = $q.defer();
            //post user data
            $http.post('/test', angular.toJson(regularUser)).then(function success(response){});

            //save to cache
            if(!CacheFactory.get('userDataCache')){
                userCache = CacheFactory.createCache('userDataCache',cacheOptions);
                userCache.put('userDataCache', userData);
            }
            else{
                userCache = CacheFactory.get('userDataCache');
                userCache.touch('userDataCache', userData);
            }
            deferred.resolve(true);
            return deferred.promise;
        },
        //get from cache
        getUserData: function(){
            if(!CacheFactory.get('userDataCache')){
                //create cache again
                userCache = CacheFactory('userDataCache');
                return userCache.get('userDataCache');
            }
            else{
                //**** On page refresh, userCache object become empty *****
                userCache = CacheFactory.get('userDataCache');
                console.log(userCache.get('userDataCache'));// **this is undefined**
                return userCache.get('userDataCache');
            }
        }
      }
}]);
AnthonyCC commented 7 years ago

you are calling touch userCache.touch('userDataCache', userData); , touch does not put the data in the cache, it just reset the timer for that key

shailv commented 7 years ago

Thank you @AnthonyCC! It is working now.