Total Price is not updating when the quantity of products increased in the cart In Ionic Ecommerce App

爷,独闯天下 提交于 2019-12-05 09:59:59

I am updating my answer after I went through the code more thoroughly (initially I suspected change detection issues, but in fact I think the issue is how totalAmount variable is handled).

If we follow your code and see what changes totalAmount var: - first it gets set to 0 within cart.ts - then it gets updated every time loadCartItems() method in cart.ts is called, where as this method takes data from persistence (Ionic Storage)

So it is naturally that when you update quantity in these methods:

decreaseProductCount(itm) {
    if (itm.count > 1) {
      itm.count--;
    }
  }

  incrementProductCount(itm) {
    itm.count++;
  } 

That totalAmount is not getting updated as you do not execute any code to do it. To update totalAmount as part of these methods I would propose to add this method:

recalculateTotalAmount() {
    let newTotalAmount = 0;
    this.cartItems.forEach( cartItem => {
        newTotalAmount += (cartItem.productPrice * cartItem.count)
    });
    this.totalAmount = newTotalAmount;
}

Now you can update total price in those methods:

decreaseProductCount(itm) {
        if (itm.count > 1) {
          itm.count--;
          this.recalculateTotalAmount();
        }
      }

incrementProductCount(itm) {
        itm.count++;
        this.recalculateTotalAmount();
      } 

UPDATE:

Also now to address the problem you mentioned in the comments ("remove the product from the cart it is not updating the totalprice and when i added the product from the product page with quantity 2, in the cart it is showing the price for the quantity 1 only and after clicking the quantity button in the cart it is updating the price.") in your loadCartItems you now can leverage same recalc method:

loadCartItems() {
    let loader = this.loadingCtrl.create({
      content: "Wait.."
    });
    loader.present();
    this.cartService
      .getCartItems()
      .then(val => {
        this.cartItems = val;
        if (this.cartItems.length > 0) {
          this.isEmptyCart = false;
          this.recalculateTotalAmount();
        }
        this.isCartItemLoaded = true;
        loader.dismiss();
      })
      .catch(err => {});
  }

PS: I also noticed that in this method you have the same calls to persistence twice:

ionViewDidLoad() {
    console.log('ionViewDidLoad CartPage');
    // I would remove the commented below as your method below does the same work
    //this.cartService.getCartItems().then((val) => {
      //this.cartItems = val;
      //console.log(val);
    //});
    this.loadCartItems();
  }

I think you should remove the first call as loadCartItems does the same work basically.

UPDATE2:

Here in removeItem method you call removeFromCart that returns promises in sequence, while you call loadCartItems after first one. To fix you can wrap two async operations into one promise.

removeItem(itm) {
    let alert = this.alertCtrl.create({
      title: 'Remove Product',
      message: 'Do you want to remove this product?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel Clicked');
          }
        },
        {
          text: 'Yes',
          handler: () => {
            this.cartService.removeFromCart(itm).then(() => {
              this.loadCartItems();
            });
          }
        }
      ]
    });
    alert.present();
  }

Reworked in provider:

removeFromCart(productdet) {
   return new Promise((resolve,reject) => {
this.getCartItems().then(result => {
      if (result) {
        var productIndex = result.indexOf(productdet);
        result.splice(productIndex, 1);
        this.storage.set(CART_KEY, result).then(()=>{ resolve() })
      }
})
})

PSS: I also feel like storing the shopping cart in persistence is fine but in your case it sort of becomes source of truth for your cart. Maybe it is best to have all the cart data in-memory and only lazily persist its data to Ionic Storage.

The totalAmount is not updating because your code never updates it ;) There are many ways to go around this. One of them is as Sergey Rudenko suggested, add a function that performs the calculation each time an item count is modified. Another way to do this is to create a pipe which performs actions like so:

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
    name: "totalAmount",
})

export class TotalAmountPipe implements PipeTransform {
   public transform(cartItems: any): number {
     if(!cartItems || !cartItems.length) {
         return 0;
     }
     return cartItems.reduce( (acc, curr) => { return acc + (curr.count * curr. productPrice)}, 0 );

   }
}

You then need to add this Pipe to your module declarations, and use replace in your html

<button color="secondary" full="" ion-button="" round="true">
          {{totalAmount}} Checkout
</button>

With

<button color="secondary" full="" ion-button="" round="true">
          {{cartItems | totalAmount}} Checkout
</button>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!