将产品添加到购物车中时出现此错误,该产品最终托管在Firebase中。我正在学习本教程,但似乎无法理解所缺少的内容。该对象是在Firebase中创建的,但是错误仍然存在,并且我无法在购物车中显示产品数量...
产品组件的TS:´
constructor(
private productService: ProductService,
private route: ActivatedRoute,
private shoppingCartService: ShoppingCartService) {
this.productService.getAll().subscribe(products => {
this.products = products;
route.queryParamMap.subscribe(params => {
this.category = params.get('category');
});
})
}
async ngOnInit() {
this.subscription = (await this.shoppingCartService.getCart())
.subscribe(cart =>{
this.cart = cart;
console.log(cart)
})
}
addToCart(product: Product){
this.cartService.addToCart(product);
console.log(this.shoppingCart)
let item = this.shoppingCart.item[this.product.$key];
console.log(item)
}
HTML:
<button
(click)="addToCart(product)"
class="btn btn-primary btn-block">
Add to cart
</button>
<div>{{getQuantity()}}</div>
服务:
constructor(private db: AngularFireDatabase) { }
private create() {
return this.db.list('/shopping-cart').push({
dateCreated: new Date().getTime()
});
}
async getCart(){
let cartId = await this.getOrCreateCartId();
return this.db.object('/shopping-cart/'+ cartId)
}
private getItem(cardId: string, productId: string){
return this.db.object('/shopping-cart/' + cardId + '/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;
}
async addToCart(product: Product) {
let cartId = await this.getOrCreateCartId();
console.log(cartId)
//get reference of product ID insinde the cart
let item$= this.getItem(cartId, product.$key);
item$.take(1).subscribe(item => {
if (item.$exists()) item$.update({ quantity: item.quantity + 1 });
else item$.set({ product: product, quantity: 1 })
});
}
如果我仅在click事件上使用create方法,则不会出现任何错误,并且具有日期时间的对象已创建,但是在提交产品对象Angular时会抱怨未定义的ID ...
编辑: 以下行中的关键字$ exist和数量
if (item.$exists()) item$.update({ quantity: item.quantity + 1 });
变红,但是VC没有代码建议
答案 0 :(得分:1)
在您的代码中,您使用的是product
,但是您引用的是this.product.$key
。尝试使用product.$key
。
addToCart(product: Product){
this.cartService.addToCart(product);
console.log(this.shoppingCart)
let item = this.shoppingCart.item[product.$key];
console.log(item)
}
答案 1 :(得分:0)
async ngOnInit() {
this.subscription = (await this.shoppingCartService.getCart())
.valueChanges()
.subscribe((cart) => (this.cart = cart));
}
请输入.valueChanges() 我认为它将起作用。 如果不起作用,请通知我。