简体   繁体   中英

How parse data from local storage in the typescript file?

I have a user-stored array in the local storage, each with login, password, role and email. This is data about registered users. I need to write this array into a variable in the typescript.I created a variable existingUsers

public existingUsers: { login: string, password: string, email: string, role: string } [];

and transferred json from local storage to it

logInUser() {
    this.existingUsers = JSON.parse(localStorage.getItem('allUsers'));
    console.log(this.existingUsers[0].login);
}

but after that all the properties existingUsers, such as login of password, are undefined. What am I doing wrong?

EDIT

let existingUsers = JSON.parse(localStorage.getItem('allUsers'));
if (existingUsers == null) {
  existingUsers = [];
}

let currentUser;
if (this.password === this.confirmPassword) {
  currentUser = {
    'login': this.login,
    'email': this.email,
    'role': this.role,
    'password': this.password,
  };
  currentUser = JSON.stringify(currentUser);
  localStorage.setItem('user', 'user');
  // Save allEntries back to local storage
  existingUsers.push(currentUser);
  localStorage.setItem('allUsers', JSON.stringify(existingUsers));

this.existingUsers is an object not an array, you need to access without using index

logInUser() {
    this.existingUsers = JSON.parse(localStorage.getItem('allUsers'));
    console.log(this.existingUsers.login);
}

EDIT

The problem lies here,

 currentUser = JSON.stringify(currentUser);
  localStorage.setItem('user', 'user');
  // Save allEntries back to local storage
  existingUsers.push(currentUser);

you are stringifying the user before pushing to the array, do it as follows,

  const User = JSON.stringify(currentUser);
  localStorage.setItem('user', User); //use different object
  // Save allEntries back to local storage
  existingUsers.push(currentUser);

now you can get existingUsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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