Reputation: 137
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 !
Upvotes: 1
Views: 8309
Reputation: 6854
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);
});
}
}
Upvotes: 2
Reputation: 9764
You are doing async HTTP call. so you need to add console.log inside subscribe.
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);
});
}
Upvotes: 0