如何在不破坏localStorage类型的情况下存储和获取对象? [英] How to store and get an object without destroying the type in localStorage?

查看:80
本文介绍了如何在不破坏localStorage类型的情况下存储和获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TypeScript处理AngularJS项目.

I'm working on an AngularJS project with TypeScript.

personPerson类的对象.我需要将person对象存储在localStorage中,并使用其类型来检索它.

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 只能存储 .您可以使用JSON序列化对象并将其取回.

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
});

这篇关于如何在不破坏localStorage类型的情况下存储和获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆