【问题标题】:Set some class object to Local Storage将一些类对象设置为本地存储
【发布时间】:2017-11-17 17:38:50
【问题描述】:

我正在使用 Angular CLI。实际上,我有注册组件: ts

...
export class User {
  first_name: string;
  second_name: string;
  email: string;
  password: string;
}
...
export class RegistrationComponent implements OnInit {
  saveValue(storageValue) {
  localStorage.setItem(`user`, new User(storageValue.first_name, storageValue.second_name));

html

<input type="text" name="first_name" [(ngModel)]="first_name">
<input type="text" name="second_name" [(ngModel)]="second_name">

所以我试图将用户对象设置为本地存储,但出现错误:提供的参数与调用目标的任何签名都不匹配。 我已经尝试过了:

...
saveValue(storageValue) {
      localStorage.setItem(`user`, new User(String(storageValue.first_name), String(storageValue.second_name));
...

...
saveValue(storageValue) {
      localStorage.setItem(`user`, JSON.stringify(new User(storageValue.first_name, storageValue.second_name));
..

但是,它不起作用。谁能帮帮我?

【问题讨论】:

    标签: typescript angular-cli


    【解决方案1】:

    你只能设置一个字符串到本地存储,所以你需要想办法序列化/反序列化你的User对象。

    序列化

    localStorage.setItem('user', JSON.stringify({
      first_name: storageValue.first_name,
      second_name: storageValue.second_name
    }));
    

    反序列化

    const raw = JSON.parse(localStorage.getItem('user'));
    const user = new User(raw.first_name, raw.second_name);
    

    【讨论】:

    • 感谢帮了大忙
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多