Here is my shopping-cart.service
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/compat/database';
import { Product } from './models/product';
import { take } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ShoppingCartService {
product:Product[] = [];
constructor(private db:AngularFireDatabase) { }
private create(){
return this.db.list('/shopping-carts/').push({
dateCreated: new Date().getTime()
});
}
private getItem(cartId: string, productId: string) {
return this.db.object<any>('/shopping-carts/' + cartId + '/items/' + productId +'/');
}
private async getOrCreateCartId() {
const cartId = localStorage.getItem('cartId');
if (cartId) { return cartId; }
let result = await this.create() as any;
localStorage.setItem('cartId', result.key!);
return result.key!;
}
async addToCart(product:Product){
let cartId = await this.getOrCreateCartId();
let itemm= this.getItem(cartId, product.key);
itemm.valueChanges().pipe(take(1)).subscribe((item:any) => {
if (item != null) {
itemm.update({ quantity: item.quantity + 1 })
}
else{
itemm.set({product:product,quantity: 1})
}
});
}
}
product-card-component.ts
import { Component, Input } from '@angular/core';
import { Product } from '../models/product';
import { ShoppingCartService } from '../shopping-cart.service';
@Component({
selector: '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:ShoppingCartService){
}
addToCart(product:Product){
this.cartService.addToCart(product);
}
}
model/product.ts
export interface Product{
key: string;
data:any;
title: string;
price: number;
category: string|null;
imageUrl:string;
}