【问题标题】:I want to calculate the sum of the ShoppingCart at Firebase with Angularfire2我想用 Angularfire2 计算 Firebase 的 ShoppingCart 的总和
【发布时间】:2016-11-27 20:46:36
【问题描述】:

我正在构建一个使用 Angular2、Firebase 和 AngularFire2 的实验性应用程序。 这是我的数据的样子:

{
  "ShoppingCartItem":
      {
        "item1":{
            "quantity": 2,
            "productId": "abc"
        },
        "item2":{
            "quantity": 1,
            "productId": "bcd"
        }
      }
  "Product"
      {
        "abc":{
            "name": "product1",
            "price": 5
    },
        "bcd":{
            "name": "product2",
            "price": 6
        }
    }
}

以下是我的购物车.ts

this.items = this.af.database.list('ShoppingCartItem')
          .map(carts => {
            return carts.map(item => {
              item.product = this.af.database.object(`Product/${item.productId}`);
              return item;
            });
          });

下面是我的购物车.html

<table>
<tbody>
    <tr *ngFor="let item of (items | async)">
        <td>{{(item.product | async)?.name}}</td>
        <td><input type="text" name="quantity" [(ngModel)]="item.quantity" size="1" class="form-control"></td>
        <td>{{(item.product | async)?.price | number: '.2'}}</td>
        <td>{{(item.product | async)?.price * item.quantity | number: '.2'}}</td>
    </tr>
</tbody>
<tfoot>
    <tr>
      <td colspan="2" class="text-right">
        <strong>Total :</strong>
      </td>
      <td colspan="2" class="text-left">
        ?????????
      </td>
    </tr>
</tfoot>

我想计算 ShoppingCart 的总和。所以我想找到数据显示的 (2*5) + (1*6) = 16 的值。我该怎么做。

这个plunker

【问题讨论】:

    标签: javascript angular firebase angularfire2


    【解决方案1】:

    问题出在这段代码中:

    carts.map(cart => {
        this.af.database.object(`Product/${cart.productId}`)
        .subscribe(d => {
            cart.product = d;
        });
      return cart;
    });
    carts.forEach(cartItem => {
        qty += cartItem.quantity;
        total += cartItem.quantity * cartItem.product.price;
        // console.log(cartItem);
    });
    

    两个调用:carts.mapcarts.forEach 是同步的,并且一个接一个地发生。但是产品的加载(通过af.database.object)是异步的,因此当您迭代尚未加载的cartItem 产品时。

    解决方案是将产品加载和总计算链接起来。见here

    【讨论】:

    • 太棒了!我正在做一个项目,我需要很多 RXJS。多亏了你,我相信我可以学到一些东西。再次感谢您。
    【解决方案2】:

    由于您使用的是 Firebase,我首先注意到的是键名。像这样修复它们。其中cart.$key 是一些哈希码,例如-KXeML1Na9qCsvK4JSyQ.

    {
      "ShoppingCartItem": {
        -KXeML1OkDyUVTAdHYPx : {
          -KXeML1OkDyUVTAdHYPx: true,
          -KXeML1PP4faQG2Z3fzU: true
        },
        -KXeML1Na9qCsvK4JSyQ: {
          -KXeML1PP4faQG2Z3fzU: true
        }
      },
      "Products": {
        -KXeML1OkDyUVTAdHYPx:{
          "name": "product1",
          "price": 5
        },
        -KXeML1PP4faQG2Z3fzU:{
          "name": "product2",
          "price": 6
        }
      }
    }
    

    现在重写你的前端逻辑。请同时编写并导出合适的Product 类。放在下面shoppingcart.service.ts

    findProductKeysForCart(cartId: string): Observable<string[]> {
     return this.database.list('ShoppingCartItem', {
        query: {
          orderByKey: true,
          equalTo: cartId
        }
      })
        //.do(console.log)// Check whats coming,
        //.map(result => result[0])// might be needed
        .map(sci => sci.map(product => product.$key));
    }
    
    findProductsForProductKeys(productKeys$: Observable<string[]>): Observable<Product[]> {
      return productKeys$
        .map(productKeys => productKeys.map(productKey => this.database.object(`Products/${productKey}`)))
        .flatMap(prodObservables => Observable.combineLatest(prodObservables));
    }
    
    
    findAllProductsForCart(cartId): Observable<Product[]> {
        //this fn gets your Products for a cart
        return this.findProductsForProductKeys(this.findProductKeysForCart(cartId));
    }
    

    现在,在产品类或订阅中进行最终计算。 下面会进入DisplayCart.component.ts

    items;
    constructor(private shoppingCartService: ShoppingCartService){}
    
    ngOnInit(){
      const items$ = this.shoppingCartService.findAllProductsForCart(this.cartId);
    
     items$.subscribe(items => this.items = items);
    }
    

    剩下的事情还需要你自己完成,祝你好运。

    【讨论】:

    • 你的方法是不同的方法。我无法列出购物车信息。我的示例在 ShoppinCartItem 表中有数量信息。产品表还带有价格信息。我想将总和乘以价格。所以我想找到数据显示的 (2*5) + (1*6) = 16 的值。我该怎么做。
    • 这个plunker。你能帮忙吗?
    • @GökmenSaralu 仍然不明白。我说你编写代码的方式非常糟糕。你需要先用正确的方式编写代码,通过上面的代码你可以很容易地得到对象。
    • 我是 Nosql 数据库、实时数据库和 RXJS 的新手。我找到了这些例子。你给你的例子从来没有考虑过数量。我不想讨论模型的结构。我想要的只是从一个文档中提取数量信息,从其他文档中提取价格信息。我想做后端计算并在前端打印。这个plunker 也提供了示例代码。您可以从控制台看到错误。感谢您的关心。
    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多