TOLULOPE ADETULA TOLULOPE ADETULA - 11 days ago 85
TypeScript Question

My code is not looping through my firebase database

The below code isn't displaying all my items quantity, it's only displaying the first item



import {ShoppingCartItem} from './shopping-cart-item';

export class ShoppingCart {
constructor(public items: ShoppingCartItem[]) {}

get totalItemsCount() {
let count = 0;
for (const productId in this.items) {
if (this.items.hasOwnProperty(productId)) {
count += this.items[productId].quantity;
return count;
}
}
}

}




Answer Source

Because you are returning inside the loop, Change it as follows,

 get totalItemsCount() {
    let count = 0;
    for (const productId in this.items) {
      if (this.items.hasOwnProperty(productId)) {
        count += this.items[productId].quantity;        
      }
    }
    return count;
  }