In Firebase database cart Id is showing undefined(check image) and only one category item added in Firebase database and when add another product not show in database but quantity is increased.
This is the shopping cart service.
please help me.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from './models/product';
//import 'rxjs/add/operator/take';
import { take } from 'rxjs/operators';
import 'rxjs/add/operator/take';
@Injectable({
providedIn: 'root'
})
export class ShoppingCardService {
constructor(private db: AngularFireDatabase) { }
private create() {
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime()
});
}
private getCart(cartId: string) {
return this.db.object('/shopping-carts/' + cartId);
}
private getItem(cartId: string, productId: string) {
return this.db.object<any>('/shopping-carts/' + cartId + '/items/' + productId);
}
private async getOrCreateCartId() {
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();
let item$ = this.getItem(cartId, product.$key);
item$.snapshotChanges().pipe(take(1)).subscribe((item: any) => {
if (item.key != null) {
item$.update({ quantity: (item.payload.val().quantity || 0) + 1 });
}
else {
item$.set({ product: product, quantity: 1 });
}
});
}
}
This is the product-card-component.ts ... In product-card-component.ts used the addToCart() method.
import { Component, OnInit, Input } from '@angular/core';
import { Product } from '../models/product';
import { ShoppingCardService } from '../shopping-card.service';
@Component({
selector: 'app-product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent {
@Input('product') product: Product;
@Input('show-actions') showActions = true;
constructor(private cartService: ShoppingCardService) { }
addToCart(product: Product) {
this.cartService.addToCart(product);
}
}
model/product.ts
export interface Product {
$key: string;
title: string;
price: number;
category: string;
imageUrl: string;
}
productIdhas an undefined value somewhere. We can't see where that is, since we don't see a call toaddToCartanywhere. You're going to have to do some debugging to figure that out. - Doug StevensonaddToCart? - Doug Stevenson