当购物车中的产品数量增加时,总价格不会更新 [英] Total Price is not updating when the quantity of products increased in the cart In Ionic Ecommerce App

查看:60
本文介绍了当购物车中的产品数量增加时,总价格不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ionic电子商务应用,并使用Laravel中制作的API.我已经在购物车中添加了产品,但是当我增加购物车中的产品数量时,产品的价格在增加,但是总价没有更新,并且从购物车中移除产品时,它也没有更新价格

I am working on the Ionic Ecommerce App and using API made in Laravel. I have added the products in the cart but when I am increasing the quantity of products in the cart, the price of product is increasing but the total price is not updating and also when removing the product from the cart, it is not updating the price.

这是我的 cart.html :

<ion-header>
  <ion-navbar color="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>
      Your Cart
    </ion-title>
  </ion-navbar>

</ion-header>

<ion-content>
  <ion-list *ngFor="let itm of cartItems" class="myitem11">
    <ion-item>
      <ion-thumbnail item-start >
        <img src="{{itm.image}}">
      </ion-thumbnail>
      <h2>{{itm.name}}</h2>
      <p>Actual Price:
        <span [ngStyle]="itm?.discountp === '0' ? {'text-decoration':'none'} : {'text-decoration':'line-through'}">
          ₹{{itm.disprice * itm.count}}
        </span>
      </p>
      <p>Discount: {{itm?.discountp}}%</p>
      <ion-row class="item-count">
        <ion-col class="qty">
            <button (click)="decreaseProductCount(itm)" clear ion-button small color="dark" class="mewbtn11">
              -
            </button>
            <button ion-button small clear color="dark" class="mewbtn11">
              {{itm?.count}}
            </button>
            <button (click)="incrementProductCount(itm)" clear ion-button small color="dark" class="mewbtn11">
              +
            </button>
        </ion-col>
      </ion-row>
      <p>Discounted Price: ₹{{itm.productPrice * itm.count}}</p>
      <button ion-button icon-only clear item-end (click)="removeItem(itm)"><ion-icon class="mycaicon11" name="ios-trash-outline"></ion-icon></button>
    </ion-item>
  </ion-list>
</ion-content>

<ion-footer class="single-footer" ngif="!isEmptyCart">

  <ion-grid>
    <ion-row>
      <ion-col class="addCart" (click)="checkpage()">
        <button color="secondary" full="" ion-button="" round="true">
          {{totalAmount}} Checkout
        </button>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-footer>

这是我的 cart.ts :

import { CheckoutPage } from './../checkout/checkout';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, AlertController } from 'ionic-angular';
import { CartProvider } from "../../providers/cart/cart";


@IonicPage()
@Component({
  selector: 'page-cart',
  templateUrl: 'cart.html',
})
export class CartPage {
 cartItems: any[] = [];
 totalAmount: number = 0;
 isCartItemLoaded: boolean = false;
 isEmptyCart: boolean = true;
 productCount: number = 1;
  constructor(public navCtrl: NavController, public navParams: NavParams, private cartService: CartProvider, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private cdr: ChangeDetectorRef) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad CartPage');
    this.cartService.getCartItems().then((val) => {
      this.cartItems = val;
      console.log(val);
    });
    this.loadCartItems();
  }

  loadCartItems() {
    let loader = this.loadingCtrl.create({
      content: "Wait.."
    });
    loader.present();
    this.cartService
      .getCartItems()
      .then(val => {
        this.cartItems = val;
        if (this.cartItems.length > 0) {
          this.cartItems.forEach((v, indx) => {
            this.totalAmount += parseInt(v.totalPrice);
            console.log(this.totalAmount);
          });
          this.cdr.detectChanges();
          this.isEmptyCart = false;
        }

        this.isCartItemLoaded = true;
        loader.dismiss();
      })
      .catch(err => {});
  }

  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();
  }

  checkpage()
  {
    this.navCtrl.push(CheckoutPage);
  }

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

  incrementProductCount(itm) {
    itm.count++;
    this.cdr.detectChanges();
  }

}

这是我的购物车服务:提供者>购物车> cart.ts :

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

const CART_KEY = 'cartItems';

@Injectable()
export class CartProvider {

  constructor(public http: HttpClient, public storage: Storage) {
    console.log('Hello CartProvider Provider');
  }

  addToCart(productdet) {
    return this.getCartItems().then(result => {
      if (result) {
        if (!this.containsObject(productdet, result)) {
          result.push(productdet);
          return this.storage.set(CART_KEY, result);
        } else {
          let index = result.findIndex(x => x.product_id == productdet.product_id);
          let prevQuantity = parseInt(result[index].count);
          productdet.count = (prevQuantity + productdet.count);
          let currentPrice = (parseInt(productdet.totalPrice));
          productdet.totalPrice = currentPrice;
          result.splice(index, 1);
          result.push(productdet);
          return this.storage.set(CART_KEY, result);
        }

      } else {
        return this.storage.set(CART_KEY, [productdet]);
      }
    })
  }

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

  removeAllCartItems() {
    return this.storage.remove(CART_KEY).then(res => {
      return res;
    });
  }


  containsObject(obj, list): boolean {
    if (!list.length) {
      return false;
    }

    if (obj == null) {
      return false;
    }
    var i;
    for (i = 0; i < list.length; i++) {
      if (list[i].product_id == obj.product_id) {
        return true;
      }
    }
    return false;
  }

  getCartItems() {
    return this.storage.get(CART_KEY);
  }
}

问题是,当我增加购物车页面中的数量时,它没有更新总价,并且在移除产品时也会发生这种情况.这是我的购物车页面的演示.它采用产品的原始价格,这就是为什么它无法更新总价.我要从购物车产品中获取总价,并且当产品数量增加时,它就是更新价格;当产品卸下时,它也将更新价格.非常感谢您的帮助.

The problem is that, When I am increasing the quantity in the cart page, it is not updating the total price and also this happens while removing the product. This is the demo of my cart page. It is taking the product original price and that's why it is not able to update the totalprice. I want to totalprice should take from the cart products and when the product quantity is incresed it is update the price and also when the product is removed it will update the price. Any help is much appreciated.

推荐答案

在我更彻底地检查了代码之后,我正在更新答案(最初我怀疑更改检测问题,但实际上我认为问题在于totalAmount变量的方式是处理).

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).

如果我们遵循您的代码,然后查看totalAmount var发生了什么变化: -首先在cart.ts中将其设置为0 -然后,每次调用cart.ts中的loadCartItems()方法时,该方法都会更新,因为该方法从持久性(离子存储)中获取数据

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++;
  } 

由于您不执行任何代码来执行此操作,因此totalAmount不会得到更新.要更新totalAmount作为这些方法的一部分,我建议添加此方法:

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();
      } 

更新:

现在也要解决您在评论中提到的问题(从购物车中删除产品不会更新总价,并且当我从数量为2的产品页面添加产品时,在购物车中会显示价格仅针对数量1,然后单击购物车中的数量按钮,它会更新价格.)在loadCartItems中,您现在可以使用相同的重新计算方法:

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:我还注意到,在此方法中,您两次对持久性进行了相同的调用:

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();
  }

我认为您应该删除第一个调用,因为loadCartItems基本上可以完成相同的工作.

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

UPDATE2:

在removeItem方法中,调用removeFromCart会按顺序返回promise,而在第一个之后调用loadCartItems.要解决此问题,您可以将两个异步操作包装成一个Promise.

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:我还觉得持久存储购物车是可以的,但是对于您而言,这成为您购物车的真理之源.也许最好将所有购物车数据存储在内存中,然后仅将其数据懒惰地保存到Ionic Storage.

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.

这篇关于当购物车中的产品数量增加时,总价格不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆