1

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?

1 Answer 1

1

Try to check after making below change :

addToCart(item: Object): void {
    this.cartItems = this.cartService.addToCart(item);
    console.log(this.cartItems.length)
    this.cartItemCount=this.cartItems.length;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's same, didn't help! I had it like this before, then I modified to above code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.