[英]TypeError: Cannot read properties of null (reading 'quantity')
shopping-cart.service.ts购物车.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:-错误:-
Getting this error in the console it removes the items from the cart when it's quantity becomes zero(products which are already present in the cart) , but when I try to add an item to the cart it doesn't lets me add the product to the cart and show's me this error in the console在控制台中收到此错误时,它会在数量为零时从购物车中删除商品(购物车中已经存在的产品),但是当我尝试将商品添加到购物车时,它不允许我将产品添加到购物车并在控制台中向我显示此错误
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)
I think its an async await issue on我认为这是一个异步等待问题
let item$ = this.getItem(cartId,product.key);
so item is undefined, which is why you have properties of **null**
所以 item 未定义,这就是为什么你有
properties of **null**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.