【发布时间】: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