I am learning Angular 6 now and now facing an observable issue that I can't understand.
Please take a look at my code below.
export class ShoppingCartComponent implements OnInit {
cart$;
products = {};
constructor(private shoppingCartService : ShoppingCartService,
public productService : ProductService) {
var subscription = from(this.shoppingCartService.getCart());
subscription.subscribe(cart => cart.subscribe(shoppingcart => {
var items = shoppingcart.items;
console.log(shoppingcart.items);
for(let key in items){
console.log(key);
this.productService.get(key).valueChanges().subscribe(product=>{
this.products[key] = product['title'];
console.log(product);
console.log(this.products);
//console.log(key);
});
}
}));
}
}
cart in subscribe is Observable< ShoppingCart>.
export class ShoppingCart {
constructor(public items: ShoppingCartItem[]){ }
get productIds(){
return Object.keys(this.items);
}
get totalItemsCount(){
let count = 0;
for (let productId in this.items)
count += this.items[productId].quantity;
return count;
}
}
export interface ShoppingCartItem{
product : Product;
quantity : number;
}
This angular app gets shoppingcart from firebase database and if I run this I get weird result. Please look at the screenshots. Products object seems to be overwritten by the last key which is cauliflower.

But if I toggle back the comment which is "console.log(key)". It works fine like below screenshot.
Is this because of let variable in for loop?
If let keyword is replaced with var, products object only has cauliflower regardless of console.log(key).
Please let me know.
Thanks,
