简体   繁体   English

如何在 angular 7 中的订阅中将变量获取到控制台?

[英]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.我试图让订阅者 function 将结果返回到另一个 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 function 中,但这也失败了。

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

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如果您使用字符串连接任何内容(在您的情况下为cartItems ) - “任何内容”都将转换为字符串所以,要么在 console.log 调用中删除连接,要么执行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM