How to implement full cart system in Ionic 3?


#1

Hello I have just created a cart system following https://www.joshmorony.com/add-to-cart-with-the-web-animations-api-in-ionic/ tutorial. I might be doing some silly mistake or my logic might be wrong. When I add same product multiple times /another element is created in object rather then modifying just the quantity of that particular element. please help… Here is my Home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ListPage } from '../list/list';

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

items : Object[] = [];
itemsInCart: Object[] = [];

constructor(public navCtrl: NavController) {

this.items = [
{ 'name': 'Hello World', quantityInCart: 0 , id: 1},
{ 'name': 'Hello1 World', quantityInCart: 0 , id: 2},
{ 'name': 'Hello2 World', quantityInCart: 0 , id: 3},
{ 'name': 'Hello3 World', quantityInCart: 0 , id: 4}
];
}

addToCart(item) {
item.quantityInCart += 1;
this.itemsInCart.push(item); 
console.log(this.itemsInCart);

localStorage.setItem('cart', JSON.stringify(this.itemsInCart));
}

goToList() {
this.navCtrl.push(ListPage);
}

}


output

I want the output to be

[{…}]0: {name: “Hello World”, quantityInCart: 2, id: 1}


#2

Your addToCart method has to go through the items already in the cart an update those instead of adding an additional item.


#3

yes, but something is not done correctly. Can you please some code example…