简体   繁体   中英

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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