pilogo
pilogo

Reputation: 85

Get data from .subscribe in Angular with REST API

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?

Upvotes: 0

Views: 1309

Answers (1)

Barremian
Barremian

Reputation: 31105

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

Upvotes: 1

Related Questions