Angular中localStorage存取用户数组报错:TypeError: .some不是函数
问题描述
我尝试将注册用户对象存储在localStorage中,但从localStorage获取或设置数组形式的值时,即使解析回对象,仍然出现.push或.some不是函数的错误,报错信息:
ERROR TypeError: this.registeredUserArray.some is not a function
相关代码如下:
import { Injectable } from '@angular/core'; import { Cart } from 'src/app/models/cart'; import { Product } from 'src/app/models/product'; import { productAndQuantity } from 'src/app/models/product-and-quantity'; import { User } from 'src/app/models/user'; @Injectable({ providedIn: 'root' }) export class CustomerService { registeredUserArray : User[]; tempCart: Cart = new Cart; purchaseHistoryCartArray: Cart[] = []; localStorageKey = "registeredUserArray"; defaultUsers : User[] = [ { username : "gss@google.com", password : "BruceWayne@123", isAdmin : true, }, { username : "test@gmail.com", password : "BruceWayne@123", isAdmin : false, tempCart: new Cart, purchaseHistoryCartArray: [] }, ] constructor() { if (JSON.parse(localStorage.getItem(this.localStorageKey)!)) { this.registeredUserArray = JSON.parse(localStorage.getItem(this.localStorageKey)! ?? []); } else { this.registeredUserArray = this.defaultUsers; localStorage.setItem(this.localStorageKey, JSON.stringify(this.defaultUsers)); } } addUser(user : User) { // this.registeredUserArray.push(user); console.log(JSON.parse(localStorage.getItem(this.localStorageKey)!)) this.registeredUserArray.push(user); // <-- 报错位置 localStorage.setItem(this.localStorageKey, JSON.stringify(this.registeredUserArray)); } }
问题原因与解决办法
- 核心问题:
registeredUserArray没有被正确初始化为数组。比如之前localStorage中存储的可能是单个用户对象而非数组,或者解析后的数据类型不符合预期,导致调用数组方法时报错。 - 修复方案:
- 严格校验初始化数据类型
修改构造函数逻辑,确保无论localStorage中是否有数据,registeredUserArray最终都是数组类型:constructor() { const storedData = localStorage.getItem(this.localStorageKey); let parsedUsers = storedData ? JSON.parse(storedData) : null; // 校验是否为数组,不是则使用默认数据 if (Array.isArray(parsedUsers)) { this.registeredUserArray = parsedUsers; } else { // 深拷贝默认数组,避免后续修改影响原默认值 this.registeredUserArray = [...this.defaultUsers]; localStorage.setItem(this.localStorageKey, JSON.stringify(this.registeredUserArray)); } } - 添加用户时做兜底校验
在addUser方法中先确认数组类型,防止意外情况:addUser(user: User) { // 兜底处理,确保是数组 if (!Array.isArray(this.registeredUserArray)) { this.registeredUserArray = []; } this.registeredUserArray.push(user); localStorage.setItem(this.localStorageKey, JSON.stringify(this.registeredUserArray)); } - 清理旧的异常数据
如果之前localStorage中存的是非数组数据,打开浏览器控制台执行以下命令清空该key:
之后重新运行项目即可。localStorage.removeItem('registeredUserArray')
- 严格校验初始化数据类型
内容的提问来源于stack exchange,提问作者Gaurav
相关产品推荐
相关产品推荐

