import { Injectable } from '@angular/core';
import { Grocery } from '../../auth/grocery.model';
export interface CartItem {
grocery: Grocery;
count: number;
amount: number;
}
export class Cart {
count: number = 0;
amount: number = 0;
items: CartItem[] = [];
}
@Injectable()
export class CartService {
cart: Cart = new Cart();
constructor(){}
/* constructor(private Cart: Cart) {
this.cart = Cart;
}*/
addGrocery(grocery: Grocery) {
console.log(this.cart);
console.log("gro" + grocery);
console.log(grocery.sno);
let item: CartItem = this.findItem(grocery.sno);
console.log("first" + item);
if (item) {
item.count++;
item.amount += grocery.cost;
console.log("item" + item.amount);
} else {
item = {
grocery: grocery,
count: 1,
amount: grocery.cost
};
console.log("else" + this.cart.items.push(item));
this.cart.items.push(item);
}
this.cart.count++;
this.cart.amount += grocery.cost;
console.log("cart" + this.cart.amount);
console.log(item);
console.log(this.cart);
return item;
}
removeProduct(grocery: Grocery) {
let item: CartItem = this.findItem(grocery.sno);
if (item) {
item.count--;
item.amount -= grocery.cost;
if (!item.count) {
this.remove(item);
}
this.cart.count--;
this.cart.amount -= grocery.cost;
}
return item;
}
removeItem(item: CartItem) {
this.remove(item);
this.cart.count -= item.count;
this.cart.amount -= item.amount;
}
findItem(id: string): CartItem {
for (let i = 0; i < this.cart.items.length; i++) {
if (this.cart.items[i].grocery.sno === id) {
return this.cart.items[i];
}
}
return null;
}
clearCart() {
this.cart.items = [];
this.cart.amount = 0;
this.cart.count = 0;
}
remove(item: CartItem) {
let indx: number = this.cart.items.indexOf(item);
if (indx !== -1) {
this.cart.items.splice(indx, 1);
}
}
}
从另一个组件调用cart变量时,购物车显示为空,且值不会增加。
addGrocery(grocery: Grocery) {
console.log(this.cart);
console.log("gro" + grocery);
console.log(grocery.sno);
let item: CartItem = this.findItem(grocery.sno);
console.log("first" + item);
if (item) {
item.count++;
item.amount += grocery.cost;
console.log("item" + item.amount);
} else {
item = {
grocery: grocery,
count: 1,
amount: grocery.cost
};
console.log("else" + this.cart.items.push(item));
this.cart.items.push(item);
}
this.cart.count++;
this.cart.amount += grocery.cost;
console.log("cart" + this.cart.amount);
console.log(item);
console.log(this.cart);
return item;
}
在上面的代码中,正在进行增量 但是在下面的代码中,它从另一个组件调用购物车时显示初始值
@Injectable()
export class CartService {
cart: Cart = new Cart();
constructor(){}