How to catch setar/catch object in localstorage?

Asked

Viewed 8,172 times

7

I’m sending a JSON object to localStorage:

window.localStorage.setItem('tarefa',aux);

And I try to get this object in another controller like this:

$scope.tarefa=window.localStorage.getItem('tarefa')

However, when showing on the console this $scope.tarefa.id (property of the object passed) gives undefined. This for this property or for any other.

1 answer

8


Turns out you can only save pairs of key/value in the localStorage/sessionStorage.

So, when trying to save an object as the value of the key tarefa what is saved is the string "[object Object]".

If you want to test, try to make a console.log, thus

console.log(window.localStorage.getItem('tarefa'));

The exit will be

"[Object Object]"


You can resolve this by converting the object to JSON before saving it to localStorage.

// Cria um json a partir do objeto "aux" 
var jsonAux = JSON.stringify(aux);

// "Seta" este json no localStorage
window.localStorage.setItem('tarefa', jsonAux);

// Recupera o json do localStorage
var jsonTarefa = window.localStorage.getItem('tarefa');

// Converte este json para objeto
var tarefa = JSON.parse(jsonTarefa);

console.log(tarefa.id);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.