簡體   English   中英

類型錯誤:無法讀取 null 的屬性(讀取“數量”)

[英]TypeError: Cannot read properties of null (reading 'quantity')

購物車.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)

我認為這是一個異步等待問題

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

所以 item 未定義,這就是為什么你有properties of **null**

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM