devconcept / ng-shopping-cart

🛒 An Angular component library to create shopping carts
https://devconcept.github.io/ng-shopping-cart/
MIT License
45 stars 53 forks source link

Only ever one item added to the cart - even when I add multiple different items #3

Closed millturnK closed 5 years ago

millturnK commented 5 years ago

Hi, even though I have multiple items in my test project which I am adding to the cart, it seems to overwrite them each time so there is always only the latest item. I have included the relevant code below. (It doesn't make any difference whether I catch the item added event and explicitly write to storage via the service or not). I have queried the items array via the service and it only ever has one item in it. It also doesn't matter whether I use local or session storage.

HTML

Card image cap
{{produce.name}}
${{produce.price}} per {{produce.measure}}

<cart-view [display]="'responsive-table'"> <cart-summary [noItemsText]="'# items'" [oneItemText]="'# items'" [manyItemsText]="'# items'">

CLASS import { Component, OnInit } from '@angular/core'; import {Produce} from './models/produce'; import {BaseCartItem, CartService} from 'ng-shopping-cart';

@Component({ selector: 'app-shop', templateUrl: './shop.component.html', styleUrls: ['./shop.component.css'] }) export class ShopComponent implements OnInit { produceArray = []; constructor(private cartService: CartService) { }

itemAdded($event) { console.log('item added called. Item = ', $event ); const item = $event; this.cartService.addItem(item); const items = this.cartService.getItems(); console.log('Items in care = ', items );

} getBaseCartItem(index: number){ const selectedProd = this.produceArray[index]; let baseCartItem = new BaseCartItem(); baseCartItem.image = selectedProd.pictureURL; baseCartItem.data = selectedProd.measure; baseCartItem.name = selectedProd.name; baseCartItem.price = selectedProd.price; baseCartItem.quantity = selectedProd.quantity; return baseCartItem;

} ngOnInit() { this.produceArray = []; const skinProd = new Produce(); skinProd.pictureURL = '../assets/cremeNight.jpg'; skinProd.quantity = 10; skinProd.name = 'Night Cream'; skinProd.price = 9; skinProd.measure = 'each';

this.produceArray.push(skinProd);

const maizeProd = new Produce();
maizeProd.pictureURL = '../assets/maizeFlour.jpg';
maizeProd.quantity = 4;
maizeProd.name = 'Maize Flour';
maizeProd.price = 15;
maizeProd.measure = '250g';

this.produceArray.push(maizeProd);

const potProd = new Produce();
potProd.pictureURL = '../assets/potatoPontiac.jpg';
potProd.quantity = 12;
potProd.name = 'Pontiac potato';
potProd.price = 7;
potProd.measure = 'kg';
this.produceArray.push(potProd);

}

}

millturnK commented 5 years ago

Never mind - I assumed the service would create an ID - I now see I need to. Working.