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?

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

but I need the data outside subscription!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.