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:-
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**
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.