cnak2
cnak2

Reputation: 1841

Can't parse localstorage angular 2

I'm trying to console.log a token I have added to localstorage. Here is the code:

  ngOnInit(){
    console.log('Member Info: ', JSON.parse(localStorage.getItem('LOCAL_TOKEN_KEY')));
  }

This looks right to me, but when I run it I get the following error.

Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1
SyntaxError: Unexpected token o in JSON at position 1

Anyone see anything wrong with this?

Upvotes: 0

Views: 536

Answers (3)

SrAxi
SrAxi

Reputation: 20005

I believe this is because your data is already an Object and has no need to be parsed again.

Simply try with this:

console.log('Member Info: ', localStorage.getItem('LOCAL_TOKEN_KEY'));

Uncaught SyntaxError: Unexpected token o in JSON at position 1

Is the typical JavaScript error for when you try to parse to JSON Object an element that is already a JSON Object.

Update:

Seems that you have issues when saving to LocalStorage, so here goes a head's up!

   // To save to LocalStorage
   localStorage.setItem('LOCAL_TOKEN_KEY', JSON.stringify({
      testData: 123
    }));

   // To read from LocalStorage
   console.log(JSON.parse(localStorage.getItem('LOCAL_TOKEN_KEY')));

To clean your LocalStorage:

Press F12 while in browser (for Chrome), go to Application tab, open the LocalStorage tab and select your application name. You'll find there your LocalStorage, remove it.

Upvotes: 2

Nobady
Nobady

Reputation: 1164

you can also try to transform the JSON object to a string:

console.log('Member Info: ', JSON.stringify(localStorage.getItem('LOCAL_TOKEN_KEY')));

Upvotes: 0

ranjeet8082
ranjeet8082

Reputation: 2359

Stringify the token before storing in local storage.

localStorage.setItem('LOCAL_TOKEN_KEY', JSON.stringify({'aa': 'bb'}));
let token = localStorage.getItem('LOCAL_TOKEN_KEY');
JSON.parse(token);

Upvotes: 1

Related Questions