How to pick up / drop object in localstorage?

4

I'm sending a JSON object to localStorage :

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

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

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

However, when displaying on the console this $scope.tarefa.id (property of the passed object) gives undefined . This is for this property or for anything else.

    
asked by anonymous 21.03.2017 / 14:49

1 answer

4

It turns out that you can only save key / value pairs in 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 console.log , this way

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

The output will be

  

"[object Object]"

You can solve 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);
    
21.03.2017 / 15:04