用户单击其他产品将其删除,但默认情况下,它是从Ionic Ecommerce App中从购物车中删除最后一个产品

时间:2019-01-22 06:33:54

标签: angular ionic-framework woocommerce ionic3

我正在使用Ionic电子商务应用程序,已将产品添加到购物车,还添加了产品的删除按钮,但是问题是,当我单击任何要删除的产品时,它总是在删除购物车中的最后一个产品。

这是我的 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>
      <p>Size: {{itm?.psize}}</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, ChangeDetectorRef } 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();
  }

}

在这个ts文件中,我具有删除功能:removeItem(itm)。

这是我的购物车服务 Providers> Cart> 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);
  }
}

问题是我已将产品添加到购物车,但是当我单击购物车中的删除按钮时,它始终会删除购物车中的最后一个产品。它应删除我们单击过的产品。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

在阅读代码时这很有意义。问题出在您的removeFromCart函数中,您可以在其中创建新的项目列表,然后尝试在其中具有其他对象和新引用的新创建的数组中找到要删除的项目的索引。

尝试这样的事情:

fit_on_texts

前提是您具有唯一的ID属性以区分您的产品