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

Can't read back from localStorage #195

Closed shairez closed 9 years ago

shairez commented 9 years ago

Code Example

http://plnkr.co/edit/ThTAB4NfstC0DOCiPflt?p=preview

Description:

I'm trying to save to the local stroage and then read from it, I followed the code examples and I think I wrote it as I should, but it should show "hello you" and instead it shows "hello world"

I see the values being saved in the localStorage, but CacheFactory doesn't seem to recognize any of them after reload

What am I doing wrong here?

caok2709 commented 9 years ago

I got same thing. Actually, not just for localStorage, sessionStorage has the same issue. I guess you can't use CacheFactory.get(CahceID).get(key) to get that value if you store value in sessionStorage or localStorage method. However, since it's store in localStorage you can get that message directly use 'localStorage.get method' It's a javascript method. no need for any dependencies.

jmdobry commented 9 years ago

You've misunderstood how angular-cache works. Items you "put" into a cache (which has been configured to use localStorage) will be saved to localStorage. The cache itself will not be saved to localStorage. A cache is a memory-only entity, its methods and behaviors can't be serialized to localStorage, so whenever your app starts again you have to check to make sure the cache has been initialized before you try to read any data from it. Change your plunker from this:

var supposedToBeCached = CacheFactory.get('test');
if (supposedToBeCached) {
  console.log('test');
  $scope.name = supposedToBeCached.get('message');
} else {
  var cache = CacheFactory('test');
  cache.put('message', 'You'); 
}

to this:

// Check to see if the cache has been initialized
var testCache = CacheFactory.get('test');

if (!testCache) {
  // Cache has not been initialized, so initialize it
  testCache = CacheFactory('test');
}

// Now we are sure the cache has been initialized,
// so let's read data from it (or write if nothing has been written yet).
$scope.name = testCache.get('message') || testCache.put('message', 'you');

Closing because I’m not sure this is an issue, if you are convinced that this is really a bug, please feel free to re-open the issue and add more information:

Otherwise support is done via the mailing list.