Angular购物车新增商品报Cannot read properties of null(reading 'quantity')错误问询
报错根因
- 当你尝试添加从未加入过购物车的新商品时,
this.db.object()指向的实时数据库路径不存在对应节点,valueChanges()触发回调时返回的item值为null - 原代码直接访问
item.quantity,没有对item为null的情况做兜底,因此抛出空指针错误
修复方案
只需要修改updateItem方法内计算quantity的逻辑,给item增加空值兜底即可,两种写法可选:
写法1(可选链,推荐TypeScript 3.7+版本使用)
把报错行改为:
let quantity = (item?.quantity || 0) + change;
写法2(兼容低版本TypeScript/ES版本)
把报错行改为:
let quantity = (item && item.quantity || 0) + change;
修复后的完整updateItem代码
private async updateItem(product:Product,change:number){ let cartId = await this.getOrCreateCartId(); let item$ = this.getItem(cartId,product.key); item$.valueChanges().take(1).subscribe((item:any)=>{ // 增加空值兜底后不会再触发报错 let quantity = (item?.quantity || 0) + change; if (quantity === 0) item$.remove(); else item$.update({ title:product.title, imageUrl:product.imageUrl, price: product.price, quantity:quantity }) }) }
补充优化建议
- 可以给
item指定明确的类型定义,替代any,开发阶段就能提前发现空值风险 - 可以使用
firstValueFrom把RxJS observable转为promise,替代subscribe写法,逻辑更统一:
private async updateItem(product:Product,change:number){ let cartId = await this.getOrCreateCartId(); let item$ = this.getItem(cartId,product.key); const item = await firstValueFrom(item$.valueChanges().pipe(take(1))); let quantity = (item?.quantity || 0) + change; if (quantity === 0) await item$.remove(); else await item$.update({ title:product.title, imageUrl:product.imageUrl, price: product.price, quantity:quantity }) }
内容的提问来源于stack exchange,提问作者Hartej Singh Assi
相关产品推荐
相关产品推荐

