You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular注入CartService读取购物车items报null类型错误如何解决

问题根因

  • 组件内observable赋值逻辑颠倒,没有正确关联服务中的购物车数据流
  • 模板未处理购物车observable的初始空值,直接访问items属性触发空指针异常

修正步骤

1. 修正组件赋值逻辑

原来的代码把服务的可观察对象直接覆盖成了组件未初始化的空可观察对象,逻辑完全颠倒,调整后代码如下:

export class CheckoutReviewComponent implements OnInit {
  // 直接关联服务暴露的购物车可观察对象即可
  cart$: Observable<ICartModel> = this.cartService.cart$;

  constructor(private cartService: CartService) { }

  ngOnInit(): void {
    // 若当前用户还未加载过购物车数据,补充主动拉取逻辑
    const cartId = localStorage.getItem('cart_id');
    if (cartId) {
      this.cartService.getCart(cartId).subscribe();
    }
  }
}

2. 修正模板空值处理

两种可选方案,推荐第二种更高效:

方案1:使用可选链运算符做空值保护

<div class="items" *ngFor="let item of (cart$|async)?.items">
  <div class="product">
    <!-- 展示逻辑 -->
  </div>
</div>

方案2:使用*ngIf提前判断+别名,避免重复触发async管道

<ng-container *ngIf="cart$ | async as cart">
  <div class="items" *ngFor="let item of cart.items">
    <div class="product">
      <!-- 展示逻辑 -->
    </div>
  </div>
  <!-- 还可以补充购物车为空时的提示 -->
  <div *ngIf="cart.items.length === 0">
    购物车暂无商品
  </div>
</ng-container>

内容的提问来源于stack exchange,提问作者pușigreen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:12:00