重复的产品正在添加到Ionic App中的“愿望清单”页面

时间:2019-01-24 05:02:57

标签: angular ionic-framework ionic3 ionic4

我正在使用Ionic Ecommerce应用程序,并且已在产品列表中添加商品,但是问题是,当我再次在商品列表中添加商品时,它会在商品列表页面中创建重复商品,而当我取消选中商品列表按钮时,它会添加相同的商品产品添加到心愿单页面,当我取消选中心愿单按钮时,它也应该从心愿单页面中删除产品。

这是我的 productdetails.html

<ion-col *ngFor="let product of this.pdeta" col-5 class="mynewcol22">
<button ion-button icon-only class="wish-list-btn card" (click)="toggleOnWishlist(product)" color="light" class="mywisbtn11">
    <ion-icon [name]="product.onWishlist ? 'ios-heart' : 'heart-outline' "></ion-icon>
</button>
</ion-col>

在此视图中。我正在用愿望清单心脏轮廓按钮显示产品。

这是我的 productdetails.t s:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController, AlertController } from 'ionic-angular';
import { CartProvider } from '../../providers/cart/cart';
import { CartPage } from '../cart/cart';
import { Storage } from '@ionic/storage';
import { WishlistPage } from '../wishlist/wishlist';

@IonicPage()
@Component({
  selector: 'page-productdetails',
  templateUrl: 'productdetails.html',
})
export class ProductdetailsPage {
  detailsp: any = [];
  pdeta: any = [];
  cartItems: any[];
  constructor(public navCtrl: NavController, public navParams: NavParams, private cartService: CartProvider, public toastCtrl: ToastController, private storage: Storage, private alertCtrl: AlertController) {
    this.detailsp = this.navParams.get('productdet');
    this.pdeta = this.detailsp.msg;
  }

  ionViewDidEnter(){
    this.getSingleProduct();
  }

  toggleOnWishlist(product){
    this.storage.get("ID").then((val) =>
    {
      if(val)
      {
       product.onWishlist = !product.onWishlist;
       this.cartService.addToWishlist(product).then((val) => {
        this.presentWishToast(product.product_name);
      });
      }
      else
      {
        this.presentAlert();
      }
    });
  }

  presentWishToast(name: any) {
    let toast = this.toastCtrl.create({
      message: `${name} has been added to wishlist`,
      showCloseButton: true,
      closeButtonText: 'View Wishlist'
    });

    toast.onDidDismiss(() => {
      this.navCtrl.push(WishlistPage);
    });
    toast.present();
  }

  presentAlert() {
    let alert = this.alertCtrl.create({
      title: 'Please Login For Wishlist',
      buttons: ['Dismiss']
    });
    alert.present();
  }

}

在这个ts文件中,我做了一个toggleOnWishlist函数,该函数会将产品添加到愿望清单页面。

这是我的 wishlist.html

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

</ion-header>


<ion-content>
  <ion-list *ngFor="let itm of wishItems" class="myitem11">
    <ion-item>
      <ion-thumbnail item-start>
        <img src="{{itm.image}}">
      </ion-thumbnail>
      <h2>{{itm.product_name}}</h2>
      <p>
        Actual Price:
        <span [ngStyle]="itm?.discount === '0' ? {'text-decoration':'none'} : {'text-decoration':'line-through'}">₹{{itm.product_price}}</span>
      </p>
      <p>Discount: {{itm?.discount}}%</p>
      <p>
        Discounted Price: ₹{{itm.product_actual_price}}
      </p>
      <button ion-button icon-only clear item-end (click)="removeWishItem(itm)">
        <ion-icon class="mycaicon11" name="ios-trash-outline"></ion-icon>
      </button>
    </ion-item>
  </ion-list>
</ion-content>

在此视图中,我正在使用“删除”按钮显示愿望清单产品。

这是我的愿望清单

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

@IonicPage()
@Component({
  selector: 'page-wishlist',
  templateUrl: 'wishlist.html',
})
export class WishlistPage {
  wishItems: any[] = [];
  isCartItemLoaded: boolean = false;
  constructor(public navCtrl: NavController, public navParams: NavParams, private cartService: CartProvider, public loadingCtrl: LoadingController, private alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WishlistPage');
    this.loadWishItems();
  }

  loadWishItems() {
    let loader = this.loadingCtrl.create({
      content: "Wait.."
    });
    loader.present();
    this.cartService
      .getWishItems()
      .then(val => {
        this.wishItems = val;
        //console.log(val);
        this.isCartItemLoaded = true;
        loader.dismiss();
      })
      .catch(err => {});
  }

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

这是我的购物车服务: Providers> Cart> cart.ts

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

const CART_KEY = 'cartItems';
const WISH_KEY = 'wishItems';

@Injectable()
export class CartProvider {

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


  addToWishlist(productwishdet) {
    return this.getWishItems().then(result => {
      if (result) {
        if (!this.containsObject(productwishdet, result)) {
          result.push(productwishdet);
          return this.storage.set(WISH_KEY, result);
        } else {
          result.push(productwishdet);
          return this.storage.set(WISH_KEY, result);
        }

      } else {
        return this.storage.set(WISH_KEY, [productwishdet]);
      }
    })
  }

  removeFromWish(productdet) {
    return this.getWishItems().then(result => {
      if (result && result.length) {
        const newList = result.filter(el => el.id !== productdet.id);
        return this.storage.set(WISH_KEY, newList);
      }
    })
}

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

  getWishItems() {
    return this.storage.get(WISH_KEY);
  }
}

问题是:当我再次在愿望清单中添加产品时,它会在愿望清单页面中创建重复的产品;当我取消选中“愿望清单”按钮时,它将在愿望清单页面中添加相同的产品;而当我取消选中“愿望清单”按钮时,它应该还将产品从愿望清单页面中删除。非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

检查此方法:

toggleOnWishlist(product) {
    this.storage.get("ID").then(val => {
      if (val) {
        if (!product.onWishlist) {
          this.cartService.addToWishlist(product).then(val => {
            this.presentWishToast(product.product_name);
          });
        } else {
          this.cartService.removeFromWish(product).then(val => {
            this.presentWishToast(product.product_name);
          });
        }
        product.onWishlist = !product.onWishlist;
      } else {
        this.presentAlert();
      }
    });
  }

在将产品添加或添加到愿望清单之前,请尝试执行此检查。

Toast消息代码:

let toast = Toast.create({
      message: "Your Message",
      duration: 1000,
      showCloseButton: true,
      closeButtonText: 'Close',
      dismissOnPageChange: true,
    });

尝试上面的代码,并根据需要使用属性。

希望这会有所帮助!