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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With