Search code examples
angularobservablesubscriber

How to get a variable to a console inside a subscribe In angular 7?


I am trying to get the result return by the subscriber function to another function. But when I console it there is only an empty array

I tried including it the ngOnInit function of the component but that also failed.

ngOnInit() {
    var  id="5d943564ca97f725c8e6b8fa";
    this.cartService.getCartById(id).subscribe(res => {
      console.log(res['product']);
      this.cartItems=res['product'];
      console.log(this.cartItems+"cartItems");
    this.cartService.changeCartItems(res['product']) ;
}, err => {
  console.log(err);
});

But i get

Array [ {…} ]
[object Object]cartItems 
[object Object]changeCartItem

Solution

  • If you concatenate anything with string (cartItems in your case) - that "anything" will be converted to string So, either remove concatenation in console.log call or do

     console.log(JSON.stringify(this.cartItems) + "cartItems");