【问题标题】:TypeError: Cannot read properties of null (reading 'quantity')TypeError:无法读取 null 的属性(读取“数量”)
【发布时间】:2021-12-07 23:35:21
【问题描述】:

shopping-cart.service.ts

async addToCart(product:Product){
    this.updateItem(product,1)
}

async removeFromCart(product:Product){
    this.updateItem(product, -1)
}
private getItem(cartId: string, productId: string) {
    return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}
private async getOrCreateCartId():Promise<string>{
    let cartId = localStorage.getItem('cartId')
    if(cartId) return cartId;

    let result = await this.create();
    localStorage.setItem('cartId',result.key!);
    return result.key!;
}

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;  // error
    if (quantity === 0) item$.remove();
    else  item$.update({
     title:product.title, 
     imageUrl:product.imageUrl, 
     price: product.price,
     quantity:quantity
   })
 })
}

错误:-
在控制台中出现此错误时,它会在数量为零时从购物车中删除商品(购物车中已经存在的产品),但是当我尝试将商品添加到购物车时,它不允许我将产品添加到购物车并在控制台中向我显示此错误

ERROR TypeError: Cannot read properties of null (reading 'quantity')
    at SafeSubscriber._next (shopping-cart.service.ts:61)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at TakeSubscriber._next (take.js:35)
    at TakeSubscriber.next (Subscriber.js:49)
    at MapSubscriber._next (map.js:35)
    at MapSubscriber.next (Subscriber.js:49)
    at Notification.observe (Notification.js:20)

【问题讨论】:

  • 你能console.log(数量)吗,请
  • 在我没有删除条件之前,它仍然显示数量为零的产品并且仍然在购物车中,对于控制台日志它显示产品的数量(因为有' 7' almonds,数字 7),但如果数量为零,则会在控制台中引发 null 错误。
  • if(item) item$.update({quantity: item.quantity + change}); else item$.set({title:product.title,imageUrl:product.imageUrl,price:product.price,quantity:1});
  • 在使用 remove 之前使用它将商品添加到购物车。

标签: angular typescript firebase firebase-realtime-database angularfire


【解决方案1】:

我认为这是一个异步等待问题

let item$ = this.getItem(cartId,product.key);

所以项目未定义,这就是为什么你有properties of **null**

【讨论】:

  • 运气还是一样的错误
  • 它后面没有分号 - 假设您尝试添加一个?可能是this.updateItem(product, -1),并且您将项目设置为-1,所以错误并导致问题 - 需要在删除 imo 中逐步执行逻辑。坚持下去/祝你好运!
  • 是的,删除方法的原因是产品数量也因 - 1 而为负值,因此必须在达到 0 时将其删除
猜你喜欢
  • 2022-01-12
  • 2021-12-04
  • 2021-12-17
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2022-11-17
相关资源
最近更新 更多