以下是示例代码:
定义购物车条目类:
export class CartItem { id: string; // 商品ID name: string; price: number; quantity: number; total: number; }
在购物车服务中添加、删除或更新购物车条目:
@Injectable()
export class CartService {
private cartCollection: AngularFirestoreCollection
constructor(private afs: AngularFirestore) {
this.cartCollection = this.afs.collection
getCart(): Observable
addToCart(item: CartItem) { const docRef = this.afs.collection('cart').doc(item.id); docRef.get().toPromise() .then(doc => { if (doc.exists) { const cartItem = doc.data() as CartItem; cartItem.quantity += item.quantity; cartItem.total += item.total; docRef.update(cartItem); } else { docRef.set(item); } }); }
removeFromCart(item: CartItem) { const docRef = this.afs.collection('cart').doc(item.id); docRef.get().toPromise() .then(doc => { if (doc.exists) { const cartItem = doc.data() as CartItem; cartItem.quantity -= item.quantity; cartItem.total -= item.total; if (cartItem.quantity