重复的产品被添加到 Ionic App 的愿望清单页面

Duplicate products are adding to the wishlist page in Ionic App

我正在开发 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.ts:

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>

在此视图中,我显示了带有删除按钮的心愿单产品。

这是我的wishlist.ts:

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

这是我的购物车服务:供应商>购物车>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);
  }
}

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

检查此方法:

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

在将产品添加到心愿单或从中删除产品之前尝试此检查。

吐司留言码:

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

尝试上面的代码并根据您的要求使用属性任何你想要的。

希望这对您有所帮助!