简体   繁体   English

将用户数据添加到本地存储只能工作一次,之后添加的 object 会被简单地覆盖? (角度 10+)

[英]Adding user data to local storage only works once, thereafter the object being added is simply overwritten? (Angular 10+)

I have a form which takes in user data.我有一个接收用户数据的表单。 I am trying to write this inputted user data to my local storage.我正在尝试将此输入的用户数据写入我的本地存储。 The first submit adds the record as expected, however, when trying to add a second record, the first records attributes are simply overwritten - do note, an array element is added, however its value is simply the id of the previous element.第一次提交按预期添加了记录,但是,当尝试添加第二条记录时,第一条记录的属性被简单地覆盖 - 请注意,添加了一个数组元素,但它的值只是前一个元素的 id。

This can be seen below:这可以在下面看到:

After adding the first user (John), my local storage is as follows:添加第一个用户(John)后,我的本地存储如下: 在此处输入图像描述

After adding my second user (Alice), my local storage is now:添加我的第二个用户(Alice)后,我的本地存储现在是: 在此处输入图像描述

I am using an interface, User:我正在使用一个界面,用户:

export interface User {
  id : number;
  firstName : string;
  secondName : string;
  title : string;
  email : string;
  userRole : string;
  password : string;
}

The code for adding to the local storage is:添加到本地存储的代码是:

user = {} as User;

onSubmit() {
    console.log(this.addUserForm.value);
    this.user = Object.assign(this.user, this.addUserForm.value);
    this.addUser(this.user);
  }

  addUser(user: any) {
    var users = [];
    if (localStorage.getItem('Users')) {
      users = JSON.parse(localStorage.getItem('Users') || '{}');
      users = [user, ...Object.keys(users)]
    }
    else {
      users = [user]
    }
    localStorage.setItem('Users', JSON.stringify(users));
  }

Any reason as to why this may be happening?关于为什么会发生这种情况的任何原因?

...Object.keys(users) will only spread the keys of your array, which are 0, 1.., to the array. ...Object.keys(users)只会将数组的键(0、1..)传播到数组。

You should just push the new user into the array like this:您应该像这样将新user推送到数组中:

users.push(user); // or users.unshift(user); if you want it to be the first element

or if you want to use the spread syntax:或者如果你想使用传播语法:

users = [user, ...users]

instead of代替

users = [user, ...Object.keys(users)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM