简体   繁体   English

如何通过在组件内部订阅变量来从可观察值存储值-Angular4

[英]How to store value from observable via subscribe to variable inside component - Angular4

I am trying to store value from observable to a variable inside the component using a service however it always has the value of undefined. 我正在尝试使用服务将值从可观察的值存储到组件内部的变量中,但是它始终具有未定义的值。 "names" inside subscribe contains value as expected. 订阅中的“名称”包含预期的值。

 this.dataClient.obsNames.subscribe(names => { this.names = names; //declared above as public names = []; }); 

What i think you have print this.names on console outside of subscribe.which is asynchronous method.due to which your getting undefined. 我认为您已经在Subscribe。之外的控制台上打印了this.names,这是异步方法。

Try this: 尝试这个:

 `this.dataClient.obsNames.subscribe(names =>{ 
      this.names = names;
      console.log(this.names);
  });`

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

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