Search code examples
jsonangularhttp-get

How can I save http get response object in angular 6


I'm new to angular and i'm trying to figure out how can I save in a local variable the response of http.get(url)

Here is my code :

export class AppComponent {

  private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
  public data;

  constructor(private http: HttpClient) { 
    this.http.get(this.url).subscribe(response => this.data = response);
    console.log(this.data); // -> The result is undefined...
  }

}

At first, I tried this.http.get(this.url).subscribe(response => console.log(response)); and that was working has expected, however an assignation doesn't work.

Thanks a lot !


Solution

  • Your code is exactly correct. The reason the console.log is not showing the response value is because it is running BEFORE the response is processed. Once the HTTP request has been started, JavaScript continues executing the current function.

    If you want to log the response, you need to do so inside the response handler

    export class AppComponent {
    
      private url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=MY_KEY&format=json&artist=The+Weeknd' ;
      public data;
    
      constructor(private http: HttpClient) { 
        this.http.get(this.url).subscribe(response => {
            this.data = response;
            console.log(this.data);
        });
      }    
    }