jmdobry/angular-cache

Cache destroyed upon page reload

Closed this issue · 5 comments

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?

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.

Oh yeah. That makes sense. Thank you!

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

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

is this a error ?

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)
}