Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //CartService
- const CART_KEY = 'cartItems';
- @Injectable()
- export class CartProvider {
- constructor(public storage: Storage) { }
- addToCart(product) {
- return this.getCartItems().then(result => {
- if (result) {
- if (!this.containsObject(product, result)) {
- result.push(product);
- return this.storage.set(CART_KEY, result);
- } else {
- let index = result.findIndex(x => x.product_id == product.product_id);
- let prevQuantity = parseInt(result[index].count);
- product.count = (prevQuantity + product.count);
- let currentPrice = (parseInt(product.totalPrice) * product.count);
- product.totalPrice = currentPrice;
- result.splice(index, 1);
- result.push(product);
- console.log(result)
- return this.storage.set(CART_KEY, result);
- }
- } else {
- console.log(product);
- return this.storage.set(CART_KEY, [product]);
- }
- })
- }
- getCartItems() {
- return this.storage.get(CART_KEY);
- }
- removeFromCart(product,i) {
- return this.getCartItems().then(result => {
- if (result) {
- result.indexOf(product);
- result.splice(i, 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;
- }
- }
- //CartPage.ts
- removeItem(itm: string, i) {
- console.log(itm);
- this.cartService.removeFromCart(itm, i).then(() =>
- this.loadCartItems()
- )
- if (this.cartItems.length > 0) {
- this.cartItems.forEach((v) => {
- this.totalAmount -= parseInt(v.totalPrice);
- });
- // this.isEmptyCart = true;
- }
- }
- //CartPage.html
- <span class="remove" (click)="removeItem(itm,i)">
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement