加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度 – 当购物车中的产品数量增加时,总价格不会更新在Ionic Eco

发布时间:2020-12-17 17:24:23 所属栏目:安全 来源:网络整理
导读:我正在研究Ionic电子商务应用程序并使用Laravel中的API.我已经在购物车中添加了产品,但是当我增加购物车中的产品数量时,产品的价格却在增加,但总价格没有更新,而且当从购物车中取出产品时,它也没有更新价格. 这是我的cart.html: ion-header ion-navbar colo
我正在研究Ionic电子商务应用程序并使用Laravel中的API.我已经在购物车中添加了产品,但是当我增加购物车中的产品数量时,产品的价格却在增加,但总价格没有更新,而且当从购物车中取出产品时,它也没有更新价格.

这是我的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>

这是我的购物车:

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

问题在于,当我增加购物车页面中的数量时,它不会更新总价格,而且在删除产品时也会发生这种情况.这是我购物车页面的演示.这是产品的原始价格,这就是为什么它无法更新总价格.我想从购物车产品中获取总价格,当产品数量增加时,它会更新价格,当产品被移除时,它将更新价格.任何帮助深表感谢.

enter image description here

解决方法

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

如果我们按照您的代码查看totalAmount var的更改:
– 首先它在cart.ts中设置为0
– 每次调用cart.ts中的loadCartItems()方法时它都会更新,此方法从持久性中获取数据(Ionic Storage)

因此,当您在这些方法中更新数量时,这自然是:

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

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

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

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

现在您可以使用这些方法更新总价:

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

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

更新:

现在还要解决您在评论中提到的问题(“从购物车中删除产品,当我从数量为2的产品页面添加产品时,在购物车中显示数量的价格只有1并且点击购物车中的数量按钮后它正在更新价格.“)在你的loadCartItems中你现在可以利用相同的recalc方法:

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:我也注意到在这种方法中你有两次持久性调用:

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基本上做同样的工作.

UPDATE2:

在removeItem方法中,您调用removeFromCart,它按顺序返回promises,而在第一个之后调用loadCartItems.要修复,您可以将两个异步操作包装到一个promise中.

removeItem(itm) {
    let alert = this.alertCtrl.create({
      title: 'Remove Product',handler: () => {
            this.cartService.removeFromCart(itm).then(() => {
              this.loadCartItems();
            });
          }
        }
      ]
    });
    alert.present();
  }

在提供者中重做:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读