首页 > 解决方案 > 当我在构造函数上实现索引签名时,我破坏了我的 Angular Fire 数据库列表

问题描述

我正在做一个项目,当我itemsMap在 的构造函数中使用内联注释时shopping-cart.ts,我不再可以在我的购物车上看到我的列表。

我认为这个问题与购物车服务中发生的映射有关。

当它来到购物车时,它会以undefined.

购物车.service.ts

async getCart (): Promise<Observable<ShoppingCart>> {
  let cartId = await this.getOrCreateCartId ();
  return this.db.object<ShoppingCart>('/shopping-carts/' + cartId).valueChanges()
  .map(cart => new ShoppingCart(cart.itemsMap));
}

购物车

import { ShoppingCartItem } from './shopping-cart-item';


export class ShoppingCart {
  items: ShoppingCartItem[] = [];


  constructor(public itemsMap: { [productId: string]: ShoppingCartItem }) {
    for (let productId in itemsMap) {
      let item = itemsMap[productId];
      this.items.push(new ShoppingCartItem(item.product, item.quantity));
    }
  }

  get totalItemsCount() {
    let count = 0;
    for (let productId in this.itemsMap) {
      if (this.itemsMap.hasOwnProperty(productId)) {
        count += this.itemsMap[productId].quantity;
      }
    }
    return count;
  }
}

购物车项目

import {Product} from './product';

export class ShoppingCartItem {
  constructor (public product: Product, public quantity: number) {}
  get totalPrice() { return this.product.price * this.quantity}
}

产品.ts

export interface Product {
    id: string;
    title: string;
    price: number;
    category: string;
    imageUrl: string;
}

购物车.html

<h1>Shopping Cart</h1>
<ng-container *ngIf='cart$ | async as cart'>
  <p>
    you have {{cart.totalItemsCount}} items in your shopping cart.
  </p>
<table class='table'>
  <thead>
    <tr>
      <th>Product</th>
      <th>Quantity</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of cart.items">
      <td>
        {{item.product.title}}
      </td>
      <td>
        {{item.quantity}}

      </td>
      <td>
        {{item.totalPrice}}
      </td>
    </tr>
  </tbody>
  </table>
</ng-container>

我想显示我的购物车列表。

标签: angular

解决方案


推荐阅读