Advertisement
multiarts

AddToCart

Sep 11th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //CartService
  2. const CART_KEY = 'cartItems';
  3.  
  4. @Injectable()
  5. export class CartProvider {
  6.  
  7.   constructor(public storage: Storage) { }
  8.  
  9.   addToCart(product) {
  10.     return this.getCartItems().then(result => {
  11.       if (result) {
  12.         if (!this.containsObject(product, result)) {
  13.           result.push(product);
  14.           return this.storage.set(CART_KEY, result);
  15.         } else {
  16.           let index = result.findIndex(x => x.product_id == product.product_id);
  17.           let prevQuantity = parseInt(result[index].count);
  18.           product.count = (prevQuantity + product.count);
  19.           let currentPrice = (parseInt(product.totalPrice) * product.count);
  20.           product.totalPrice = currentPrice;
  21.           result.splice(index, 1);
  22.           result.push(product);
  23.           console.log(result)
  24.           return this.storage.set(CART_KEY, result);
  25.         }
  26.  
  27.       } else {
  28.         console.log(product);
  29.         return this.storage.set(CART_KEY, [product]);
  30.       }
  31.     })
  32.   }
  33.  
  34.   getCartItems() {
  35.     return this.storage.get(CART_KEY);
  36.   }
  37.  
  38.   removeFromCart(product,i) {
  39.     return this.getCartItems().then(result => {
  40.       if (result) {
  41.         result.indexOf(product);
  42.         result.splice(i, 1);
  43.         return this.storage.set(CART_KEY, result);
  44.       }
  45.     })
  46.   }
  47.  
  48.   removeAllCartItems() {
  49.     return this.storage.remove(CART_KEY).then(res => {
  50.       return res;
  51.     });
  52.   }
  53.  
  54.   containsObject(obj, list): boolean {
  55.     if (!list.length) {
  56.       return false;
  57.     }
  58.  
  59.     if (obj == null) {
  60.       return false;
  61.     }
  62.     var i;
  63.     for (i = 0; i < list.length; i++) {
  64.       if (list[i].product_id == obj.product_id) {
  65.         return true;
  66.       }
  67.     }
  68.     return false;
  69.   }
  70.  
  71. }
  72. //CartPage.ts
  73. removeItem(itm: string, i) {
  74.     console.log(itm);
  75.     this.cartService.removeFromCart(itm, i).then(() =>
  76.       this.loadCartItems()
  77.     )
  78.     if (this.cartItems.length > 0) {
  79.       this.cartItems.forEach((v) => {
  80.         this.totalAmount -= parseInt(v.totalPrice);
  81.       });
  82.       // this.isEmptyCart = true;
  83.     }
  84.   }
  85.  
  86. //CartPage.html
  87.  <span class="remove" (click)="removeItem(itm,i)">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement