TypeError:无法读取属性' -KzhZRTUYIXTdH0Zgxz4'未定义的

时间:2017-11-29 21:09:19

标签: javascript angular firebase

我收到了一个有趣的错误,我不知道它来自哪里。 我已经完成了代码并且还没有能够继续

这是ProductCard.component.ts



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

@Component({
  selector: 'app-product-card',
  templateUrl: './product-card.component.html',
  styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent implements OnInit {
    @Input('product') product: Product;
    @Input('showActions') showActions = true;
    @Input('shoppingCart') shoppingCart;
  constructor(private cartService: ShoppingCartService) { }

  ngOnInit() {

  }
  addToCart(product: Product) {
    this.cartService.addToCart(product);
  }
  getQuantity() {
    if (!this.shoppingCart) {return 0; }
    const item = this.shoppingCart.items[this.product.$key];
    return item ? item.quantity : 0;
  }
}

This is the ProductCard.component.html

<div *ngIf="product.title" class="card">
  <img *ngIf="product.imageUrl" class="card-img-top" src="{{ product.imageUrl}}" alt="{{ product.title}}">
  <div class="card-body">
    <h4 class="card-title">{{ product.title}}</h4>
    <p class="card-text">{{ product.price | currency:'NGN':true}}</p>
  </div>
  <div *ngIf="showActions" class="card-footer">
    <button
      *ngIf="getQuantity() === 0; else updateQuantity"
        (click)="addToCart(product)"
      class="btn btn-block btn-primary">Add to Cart</button>
    <ng-template #updateQuantity>
      <div class="row">
        <div class="col-2">
          <button class="btn btn-secondary btn-block">-</button>
        </div>
        <div class="col">
          {{getQuantity()}}
        </div>
        <div class="col-2">
          <button class="btn btn-secondary btn-block">+</button>
        </div>
      </div>
    </ng-template>
  </div>
</div>
&#13;
&#13;
&#13;

我从chrome dev控制台获得的错误

&#13;
&#13;
ProductCardComponent.ngfactory.js:53 ERROR TypeError: Cannot read property '-KzhZRTUYIXTdH0Zgxz4' of undefined
    at ProductCardComponent.webpackJsonp.../../../../../src/app/product-card/product-card.component.ts.ProductCardComponent.getQuantity (main.bundle.js:1293)
    at Object.eval [as updateDirectives] (ProductCardComponent.ngfactory.js:60)
    at Object.debugUpdateDirectives [as updateDirectives] (vendor.bundle.js:109317)
    at checkAndUpdateView (vendor.bundle.js:108501)
    at callViewAction (vendor.bundle.js:108849)
    at execEmbeddedViewsAction (vendor.bundle.js:108807)
    at checkAndUpdateView (vendor.bundle.js:108502)
    at callViewAction (vendor.bundle.js:108849)
    at execEmbeddedViewsAction (vendor.bundle.js:108807)
    at checkAndUpdateView (vendor.bundle.js:108502)
&#13;
&#13;
&#13;

如果您想查看整个代码This the link to my repo on github

1 个答案:

答案 0 :(得分:0)

const item = this.shoppingCart.items[this.product.$key];

这一行会导致错误,因为密钥已被删除,因此您必须从本地存储中手动从 firebase 中删除它并创建新的购物车;