0

I'm trying to implement GET method inside Angular like this:

let resp = this.http.get("http://localhost:8082/voltage");
resp.subscribe((data)=> {this.message=data; console.log(data);});
console.log(this.message);

I get this.message as 'undefined'. From lot of other similar questions, I understood that this is an async call and data is not returned by the time I'm printing it.

How can implement a callback and get the data into a variable for accessing at later time?

ruth
  • 29,535
  • 4
  • 30
  • 57
pilogo
  • 85
  • 10
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mbojko May 26 '20 at 13:44

1 Answers1

1

You are accessing asynchronous data. As such all funcitionality that depend on the async data should be inside the subscription.

resp.subscribe((data)=> {
  this.message=data; console.log(data);
  console.log(this.message);    // <-- inside the subscription
});

More info on asynchronous data: https://stackoverflow.com/a/14220323/6513921

ruth
  • 29,535
  • 4
  • 30
  • 57
  • but I need the data outside subscription! – pilogo May 26 '20 at 13:43
  • There are workarounds, but you need to show more code. It depends on how you want to access the data outside this HTTP call. But regardless, there will almost always be a subscription involved, that is how async data works. – ruth May 26 '20 at 13:45