Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and get an object without destroying the type in localStorage?

I'm working on an AngularJS project with TypeScript.

A person is an object of the Person class. I need to store person object in localStorage and retrieve it with its type.

like image 591
Mark Timothy Avatar asked Dec 04 '15 08:12

Mark Timothy


1 Answers

window.localStorage can store only strings. You can use JSON to serialize your object and retrieve it back.

class Person {

    constructor(public name:string) {

    }
}

let person = new Person('Peter');
localStorage.setItem('person', JSON.stringify(person));
let personFromStorage = JSON.parse(localStorage.getItem('person')) as Person;

console.log({
    person: person,
    personFromStorage: personFromStorage
});
like image 139
Martin Vseticka Avatar answered Oct 11 '22 13:10

Martin Vseticka