0

Here's the service

.factory('$localstorage', ['$window', function($window) {
  return {

    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
},
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}]);

and I do console.log($localstorage.getObject('name')); it gave me an error saying Unexpected token [

Here's how my key and value look like as localstorage

{["a","b","c"]}

what's wrong actually?

Alice Xu
  • 533
  • 6
  • 20

1 Answers1

0

You must make sure your objects are properly stored with the JSON.stringify method. However if you are saving manually be sure to use a valid format.

//Correct usage to store JSON objects

saveObject: function(key, value){
    $window.localStorage[key] = JSON.stringify(value);
},

getObject: function(key) {
    var result = {};
    try{
        result = JSON.parse($window.localStorage[key] || '{}');
    }catch(e){
        console.log("JSON invalid format", e)
    }
    return result;
}
Community
  • 1
  • 1