0

I'm a bit new to angular and I have a problem where I can console.log the response from a "get", but when I try to save it to a variable, the variable is always empty. Something to do with it being asynchronous I think because I see the console trying to print out the response variable before it prints out data from inside the subscribe. This is just bare bones code but I think it demonstrates my problem.

response;

constructor(private http: HttpClient) {
this.getResponse();
console.log(response);
}

getResponse() {
return this.http.get(URL).subscribe((data) => {
this.response = data;
console.log(data);
);
}

In this example, the second console log, console.log(data), prints out the appropriate response but the first one, console.log(response), is blank. What's frustrating is every single stack overflow response I've found about using http get simply console logs the response instead of showing how to properly store the response and access it later! What do I need to do to store the response from the get into a variable and then be able to work with that variable?

  • 2
    the first console.log is blank because the info is not there yet, it's an async call and it takes some time to get the response and execute the callback – jeprubio May 13 '20 at 15:36
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – jeprubio May 13 '20 at 15:42

2 Answers2

0

try it like this, and try to check rather you get an response from your request

let response: string = "blue";

constructor(private http: HttpClient) {
this.getResponse();
console.log(response);
}

getResponse() {
return this.http.get(URL).subscribe((data) => {
this.response = data.toString;
console.log(data);
);
}
0

I recommend implementing your backend call in ngOnInit. Http requests are async tasks, which means it takes some time getting the response, thats why yur first console.log(response) is null because the answer hasnt happened yet. If you want to store the receiving data, try this:

  response;

  constructor(private http: HttpClient) {

  }

  ngOnInit() {
    return this.http.get(URL).subscribe((data) => {
      this.response = data;
      console.log(response);
      );
  }

}

You can also work with promises and await the response but you dont have to, this should work

okihnjo
  • 428
  • 3
  • 11