The flow of operations relevant for this problem is as follows: Home component calls a method in Cart component and Cart component calls a method in Cart service.
Home template:
<button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent" (click)="addToCart(specific_hall)">Add to cart</button>
Home component:
export class Home {
halls: Object;
specific_hall: Object;
cart : any;
public cartInstance: Cart= new Cart(this.cartService);
constructor(private homeService: HomeService, private cartService: CartService){
this.cart=[];
}
addToCart(item: any){
this.cart.push(item)
this.cartInstance.addToCart(item)
}
}
I have a Cart component as follows:
export class Cart {
cartItems: any;
cartItemCount : number;
constructor(private cartService: CartService){
this.cartItems=[];
this.cartItemCount=0;
}
addToCart(item: Object): void {
this.cartItems.push(this.cartService.addToCart(item))
console.log(this.cartItems.length)
this.cartItemCount=this.cartItems.length;
}
}
My cart service is as follows:
export class CartService{
cart : any;
constructor(){
this.cart=[];
}
addToCart(item: any): any {
this.cart.push(item);
return this.cart;
}
}
cart template has following code:
<span> Items in the cart: {{cartItemCount}} </span>
Even if I add elements to the cart my cart template always shows 0 in the above line. console.log(this.cartItems.length) this line in cart template however always shows correct number.
What am I doing wrong?