无法读取 null 的 属性 'items' - 从购物车注入

Cannot read property 'items' of null - injecting from cart

我试图在另一个组件中从我的购物车中获取商品,以便我可以显示它们。这就是我所做的:

我注入了 cartService 并得到了购物车:

export class CheckoutReviewComponent implements OnInit {
  cart$: Observable<ICartModel>;

  constructor(private cartService: CartService) { }

  ngOnInit(): void {
    this.cartService.cart$ = this.cart$;
  }
}

在 html 文件夹中,我遍历了项目以显示它们:

<div class="items" *ngFor="let item of (cart$|async).items">
        <div class="product">
               **display
        </div>
</div>

在控制台中我收到一条错误消息“无法读取 属性 'items' of null”。所以我没有正确地得到它们。在另一个组件中,一切都运行良好。那么我应该怎么做才能从其他组件中获取它们呢?

购物车服务:

export class CartService {
  url = 'https://localhost:5001/api/'
  private cartBS = new BehaviorSubject<ICartModel>(null);
  private totalBS = new BehaviorSubject<ICartTotal>(null);
  cart$ = this.cartBS.asObservable();
  total$ = this.totalBS.asObservable();

  constructor(private http: HttpClient) { }

  getCart(id: string) {
    return this.http.get(this.url + 'cart?cartId=' + id).pipe(
      map((cart: ICartModel)=> {
        this.cartBS.next(cart);
        this.calculateTotal();
      })
    );
  }

  updateCart(cart: ICartModel) {
    return this.http.post(this.url + 'cart', cart).subscribe(
      (response: ICartModel)=>{
         this.cartBS.next(response);
         this.calculateTotal();
        }, error => console.log(error)
      );
  }
  deleteCart(cart: ICartModel) {
    return this.http.delete(this.url + 'cart?cartId=' + cart.id).subscribe(() => {
      this.cartBS.next(null);
      this.totalBS.next(null);
      localStorage.removeItem('cart_id'); },
      error => console.log(error) );
  }

  incrementQuantity(item: ICartItem) {
    const cart = this.cartBS.value;
    const itemIndex = cart.items.findIndex(x => x.id === item.id);
    cart.items[itemIndex].quantity++;
    this.updateCart(cart);
  }

  decrementQuantity(item: ICartItem) {
    const cart = this.cartBS.value;
    const itemIndex = cart.items.findIndex(x => x.id === item.id);
    if(cart.items[itemIndex].quantity > 1) {
      cart.items[itemIndex].quantity--;
      this.updateCart(cart);
    } else {
      this.removeItem(item);
    }
  }

  removeItem(item: ICartItem) {
    const cart = this.cartBS.value;
    if ( cart.items.some(x => x.id === item.id ) ) {
      cart.items = cart.items.filter(i => i.id !== item.id);
      if ( cart.items.length > 0) {
        this.updateCart(cart);
      } else {
        this.deleteCart(cart);
      }
    }
  }

  addToCart(item: IGemModel, quantity = 1) {
    const itemAdded: ICartItem = this.mapGemToCartItem(item, quantity);
    const cart = this.cartBS.value ?? this.createCart();
    const itemIndex = cart.items.findIndex(i=> i.id === itemAdded.id);
    if(itemIndex === -1 ){
      cart.items.push(itemAdded);
    }     
    else {
      cart.items[itemIndex].quantity += quantity;
    }
    this.updateCart(cart);
  }

  mapGemToCartItem(item: IGemModel, quantity: number): ICartItem {
    return {
      id: item.id,
      name: item.name,
      price: item.price,
      quantity: quantity,
      picture: item.picture
    };
  }

  private createCart(){
    const cart = new Cart();
    localStorage.setItem('cart_id', cart.id);
    return cart;
  }

  private calculateTotal() {
    const cart = this.cartBS.value;
    const shipping =0;
    const subtotal = cart.items.reduce((a,b)=> (b.price * b.quantity) + a, 0);
    const total = subtotal + shipping;
    this.totalBS.next({shipping, subtotal, total});
  }
}

问题在这里:

 private cartBS = new BehaviorSubject<ICartModel>(null);

您正在发送一个 null 的初始值,您的组件会收到该值。

您可以初始化为空购物车对象而不是 null:

 private cartBS = new BehaviorSubject<ICartModel>({items: []});

或者您可以在组件中过滤:

this.cart$ = this.cartService.cart$.pipe(filter(c => !!c));