jmdobry/angular-cache

Can't read back from localStorage

Closed this issue · 2 comments

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?

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.

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:

  • good - Your versions of Angular, Angular-cache, etc, relevant console logs/error, code examples that revealed the issue
  • better - A plnkr, fiddle, or bin that demonstrates the issue
  • best - A Pull Request that fixes the issue, including test coverage for the issue and the fix

Otherwise support is done via the mailing list.