【问题标题】:An empty array is being pushed to localStorage instead of data一个空数组被推送到 localStorage 而不是数据
【发布时间】:2025-12-28 13:00:06
【问题描述】:

我有一个使用 localStorage 具有 CRUD 功能的 Angular 应用程序。我需要从几个输入字段中收集一个名为 rubberboot 的数据对象,并将其推送到包含对象数组的 localStorage 键 rubbberboots

这里是 Stackblitz:https://stackblitz.com/edit/github-4lgqkx

使用 lisaa.component.ts 中的输入字段,数据应该是

{ name: "foo", color: "bar", price: 123, availability: 123 }

但是一个空数组被推送到 localStorage

[[]]

kumpparit.service.ts中的这段代码将rubberboot推送到localStorage:

addRubberboot = (rubberboot: rubberboot) => {
    if (typeof (Storage) != undefined) {
      let rubberboots = JSON.parse(localStorage.getItem("rubberboots"));
      rubberboot.id = this.generateId();

      rubberboots.push(rubberboot);
      localStorage.setItem("rubberboots", JSON.stringify(rubberboots));
    }
  }

这个函数为rubberboot对象生成一个id,因为id来自localStorage而不是输入字段:

generateId = () => {
    if (typeof (Storage) != undefined) {
      let rubberboots: rubberboot[] = JSON.parse(localStorage.getItem("rubberboots"));
      let index = 0;
      for (let rubberboot of rubberboots) {
        index++;
      }
      return index;
    }
  }

我希望 localStorage 键 rubberboot 现在保留

的值
[ { name: "foo", color: "bar", price: 123, availability: 123, id: 0 } ]

下一次对 localStorage 的推送操作会将 rubberboot 键的值设置为

[ 
    { name: "foo", color: "bar", price: 123, availability: 123, id: 0 },
    { name: "foo", color: "bar", price: 123, availability: 123, id: 1 } 
]

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    问题是您将ruberboot 定义为一个数组,并在您的LisaaComponent 中为其分配一个数组,而不是您的组件中的一个对象。然后序列化尝试序列化一个数组数组。

    把它改成这个(我添加了一些初始化器,如果你愿意,你可以改变定义以允许属性的未定义值)。

    rubberboot: rubberboot = {availability: 0, color: '', name: '', price: 0, id: 0};
    

    原来你有:

    rubberboot: rubberboot[] = [];
    

    您更新的stackblitz

    【讨论】: