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

Cache destroyed upon page reload #160

Closed demisx closed 9 years ago

demisx commented 9 years ago

I create a new cache in Angular 1.4 .run block like this:

if (!DSCacheFactory.get('authCache')) {
  DSCacheFactory('authCache', {
    maxAge: 120 * 60 * 1000, // 2hrs
    deleteOnExpire: 'aggressive',
    storageMode: 'localStorage',
  }
});

However, each time I hit reload button in the browser, the DSCacheFactory.get('authCache') returns undefined and a new instance is created. I thought this cache should persist for 2 hours. Am I missing something?

jmdobry commented 9 years ago

I thought this cache should persist for 2 hours. Am I missing something?

Any data you save in the cache is persisted, but when you reload the page, all your javascript (stuff in memory) gets thrown away, so the authCache has to be re-created in memory, at which point it will reload whatever was stored in localStorage.

demisx commented 9 years ago

Oh yeah. That makes sense. Thank you!

bmrobin commented 9 years ago

this does make sense after having it explained here, but it was not intuitive when reading the README. i just started using this (helpful) library and i have been structuring my controllers to perform checks like this one to determine if there was data in localStorage or not. i couldn't figure out why if (!CacheFactory.get('myCache')) was always returning true on page refresh, despite inspecting the cache later to discover that myCache had the stored values i wanted.

what is the recommended approach for retrieving this information after page refresh in a "safe" way that will allow me to either use the object from localStorage or create a new one?

askie commented 8 years ago

CacheFactory.get('myCache').put("a","aaaaaaa"); after page reload or refresh CacheFactory.get('myCache') return undifined

is this a error ?

jmdobry commented 8 years ago

Nope, that's how it works. You need to instantiate the cache object every time your app starts, e.g.:

if (!CacheFactory.get('myCache')) {
  CacheFactory.createCache('myCache', options)
}