将产品添加到购物车中的角度6

时间:2018-09-24 08:54:20

标签: angular firebase-realtime-database

我试图将产品添加到购物车,但我得到:'$ exists属性在AngularFireObject类型上不存在'。产品已添加到购物车,但是如果它存在于购物车中,则只会更新数量。我在firebase中使用angular 6,但是我正在使用的教程在angular 4中。

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Product } from '../models/product';
import { take } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService {
  constructor(private db: AngularFireDatabase) { }

  private create() {
   return  this.db.list('/shopping-carts').push({
      dateCreated: new Date().getTime()
    });
  }

 async getCart() {
   const cartId = await this.getOrCreateCartId();
  return this.db.object('/shopping-carts/' + cartId).valueChanges();
}

private getItem(cartId, productId: string) {
  return this.db.object('/shopping-carts/' + cartId + '/items/' + productId);
}

  private async getOrCreateCartId(): Promise<string> {
    const cartId = localStorage.getItem('cartId');
    if (cartId) { return cartId; }
    const result = await this.create();
    localStorage.setItem('cartId', result.key);
    return result.key;

  }

 async addToCart(product: Product) {
     const cartId =  await this.getOrCreateCartId();
     const item$ = this.getItem(cartId, product.key);
     item$.pipe(take(1)).subscribe(
       item => {
         if(item$.$exists) {
           item$.update({ quantity: quantity + 1 });
         } else {
           item$.set({ product: product, quantity: 1});
         }
       }
     );
  }
}

shopping-cart.service.ts =>

import { Component, Input } from '@angular/core';
import { Product } from '../models/product';
import { ShoppingCartService } from '../services/shopping-cart.service';

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.css']
})

    export class ProductCardComponent {
      @Input('product') product: Product;
      @Input() showActions = true;
      @ Input() shoppingCart;

      constructor(private cartService: ShoppingCartService) { }

      addToCart() {
        this.cartService.addToCart(this.product);
      }

      getQuantity() {
        if (!this.shoppingCart) { return 0; }
        const item = this.shoppingCart.items[this.product.key];

        return item ? item.quantity : 0;
      }

}

product-card.components.ts =>

1 个答案:

答案 0 :(得分:0)

您需要使用id代替item$.$exists