首页 > 解决方案 > 错误类型错误:无法读取未定义的属性“-LlWio7vFBuxfeviKdWa”

问题描述

将产品添加到最终托管在 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 })

    });
  }

如果我只在点击事件上使用 create 方法,我不会收到任何错误,并且会创建具有日期时间的对象,但是在提交产品对象时,Angular 会抱怨未定义的 id ...

编辑:以下行中的关键字 $exist 和数量

if (item.$exists()) item$.update({ quantity: item.quantity + 1 });

变红,但 VC 没有代码建议

标签: javascriptangularfirebasefirebase-realtime-database

解决方案


在您的代码中,您正在接受 a 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)
}

推荐阅读