Angular本地存储添加用户后仅能登录最后一个用户,原因何在?
Angular注册表单localStorage存储问题:仅最后一条用户可登录
问题描述
开发Angular注册表单时,用户数据能存入localStorage,但登录时只能使用最后一条存储的用户记录验证,无法匹配之前注册的用户。
问题根源
问题出在UserServiceService的addUser方法中,处理已有用户列表时错误地创建了嵌套数组:
原用户服务类代码
import { Injectable } from '@angular/core'; import { User } from '../model/user'; @Injectable({ providedIn: 'root' }) export class UserServiceService { constructor() { } addUser(user: User) { let users = []; if(localStorage.getItem('Users')) { users = JSON.parse(localStorage.getItem('Users') as string); // 错误:将原用户数组作为单个元素放入新数组,导致嵌套结构 users = [user, ...[users]]; } else { users = [user]; } localStorage.setItem('Users', JSON.stringify(users)) } }
第一次添加用户后,localStorage存储[user1];第二次添加时,原数组[user1]被当成单个元素,生成新数组[user2, [user1]];第三次添加则变成[user3, [user2, [user1]]]。这种嵌套结构导致登录逻辑只能访问最外层数组的第一个元素(即最后添加的用户)。
修复方案
修改addUser方法中合并数组的逻辑,直接展开原用户数组,保持数据结构扁平:
修复后的用户服务类代码
import { Injectable } from '@angular/core'; import { User } from '../model/user'; @Injectable({ providedIn: 'root' }) export class UserServiceService { constructor() { } addUser(user: User) { let users = []; if(localStorage.getItem('Users')) { users = JSON.parse(localStorage.getItem('Users') as string); // 正确:直接展开原数组,避免嵌套 users = [user, ...users]; // 若希望新用户添加到数组末尾,也可使用push: // users.push(user); } else { users = [user]; } localStorage.setItem('Users', JSON.stringify(users)) } }
修改后,localStorage中的数组始终是扁平结构(如[user3, user2, user1]或[user1, user2, user3]),登录时就能遍历所有用户记录进行验证。
注册组件代码(参考)
onSubmit() { this.userSubmitted = true; if (this.registerationForm.valid) { if (this.adminPass.value === environment.adminPass){ this.UserServiceService.addUser(this.userData()); this.registerationForm.reset(); this.userSubmitted = false; this.alertify.success('You have registered successfully!'); } else{ this.alertify.error('You need to be an admin! Enter the correct admin password!'); } } else{ this.alertify.error('Please fill all required fields!'); } } userData(): User{ return this.user = { userName: this.userName.value, countrycode: this.countrycode.toString(), email: this.email.value, password: this.password.value, mobile: this.mobile.value } }
内容的提问来源于stack exchange,提问作者taleen wahdan
相关产品推荐
相关产品推荐

