我在本地存储中有一个用户存储的数组,每个数组都有登录名,密码,角色和电子邮件。这是有关注册用户的数据。我需要将此数组写入打字稿中的变量中。我创建了一个变量existingUsers
public existingUsers: { login: string, password: string, email: string, role: string } [];
并将json从本地存储转移到其中
logInUser() {
this.existingUsers = JSON.parse(localStorage.getItem('allUsers'));
console.log(this.existingUsers[0].login);
}
,但是此后未定义所有现存用户属性(例如密码登录)。我在做什么错了?
编辑
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));
答案 0 :(得分:3)
this.existingUsers
是不是数组的对象,您需要不使用 index
logInUser() {
this.existingUsers = JSON.parse(localStorage.getItem('allUsers'));
console.log(this.existingUsers.login);
}
编辑
问题出在这里,
currentUser = JSON.stringify(currentUser);
localStorage.setItem('user', 'user');
// Save allEntries back to local storage
existingUsers.push(currentUser);
您要在推送到数组之前对用户进行字符串化,请按以下步骤操作
const User = JSON.stringify(currentUser);
localStorage.setItem('user', User); //use different object
// Save allEntries back to local storage
existingUsers.push(currentUser);
现在您可以获取 existingUsers