I have a cart-service and 2 components. The product-list component displays the products with a buy button. The top-bar component should display the count but it doesn't work if I getItemCount() directly. What's the issue? I want to get the length/count and not the entire array. Thanks for the help!!!
I also have the code on stackbliz.
@Component({
  selector: 'app-top-bar',
  template: `
    Item Count: {{ itemCount }}<br>
    Items: {{ items | json }}
  `
})
export class TopBarComponent implements OnInit {
  itemCount: number = 0;
  items: string[] = [];
  constructor(private cartService: CartService) { }
  ngOnInit() {
    this.items = this.cartService.getItems();
    this.itemCount = this.cartService.getItemCount();
  }
}
@Component({
  selector: 'app-product-list',
  template: `
    <div>
      <button (click)="addToCart('New Stuff')">Buy</button>
    </div>
  `
})
export class ProductListComponent {
  products: string[];
  constructor(private cartService: CartService) { }
  addToCart(item: string) {
    this.cartService.addItem(item);
  }
}
export class CartService {
  private items: string[] = [ 'One', 'Two'];
  getItems(): string[] {
    return this.items;
  }
  getItemCount(): number {
    return this.items.length;
  }
  addItem(item: string) {
    this.items.push(item);
  }
}
 
     
    