簡體   English   中英

無法計算購物車中的總數

[英]Unable to calculate total in shopping cart

我正在創建一個簡單的購物車應用程序,當用戶添加多個相同產品時。 我無法計算總數。

以下是我的邏輯,

產品數據結構,

product = {
      'productName': 'Sample Product',
      'productImage': productImage,
      'rate': 100,
      'quantity': 1
    }

this.addToCartService.cartItems.subscribe(product => {
  if (product) {
    const productExistInCart = this.cartItems.find(({ productName }) => productName === product.productName);
    if (!productExistInCart) {
      this.cartItems.push(product);
      return;
    } else {
      productExistInCart.quantity++
    }
    this.totalPrice = this.cartItems
      .map(item => item.rate)
      .reduce((prev, curr) => prev + curr, 0);
  }
});

HTML

 <div class="cart_box dropdown-menu dropdown-menu-right show">
    <ul class="cart_list" *ngIf="cartItems.length">
      <li *ngFor="let cartItem of cartItems; let i = index">
        <a (click)="removeFromCart(i)" class="item_remove"><i class="ion-close"></i></a>
        <a href="#"><img src="{{cartItem.productImage}}" alt="cart_thumb1">{{cartItem.productName}}</a>
        <span class="cart_quantity"> {{cartItem.quantity}} x <span class="cart_amount"> <span
              class="price_symbole">₹</span>{{cartItem.rate}}</span></span>
      </li>
    </ul>
    <div class="cart_footer">
      <p class="cart_total">Total: <span class="cart_amount"> <span
            class="price_symbole">₹</span>{{totalPrice}}</span>
      </p>
      <p class="cart_buttons"><a href="cart.html" class="btn btn-default btn-radius view-cart">View Cart</a><a
          href="checkout.html" class="btn btn-dark btn-radius checkout">Checkout</a></p>
    </div>
  </div>

我被困在這里,我不知道如何更新現有項目的總數。 請幫忙。

當前 output 是

在此處輸入圖像描述

根據上圖,總數應為 400。但顯示為 100。

問題是您在計算總價時沒有考慮quantity 要解決此問題,請嘗試以下操作:

        this.totalPrice = (this.cartItems
          .map(item => item.rate* item.quantity)
          .reduce((prev, curr) => prev + curr, 0));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM