如何保存Angular 6中的http获取响应对象

时间:2018-08-31 18:03:04

标签: json angular http-get

我是angular的新手,我想弄清楚如何将http.get(url)的响应保存在局部变量中

这是我的代码:

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...
  }

}

起初,我尝试了this.http.get(this.url).subscribe(response => console.log(response));,并且可以正常工作,但是分配不起作用。

非常感谢!

2 个答案:

答案 0 :(得分:0)

您正在执行异步HTTP调用。因此您需要在subscribe中添加console.log。

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);
    });
  }

答案 1 :(得分:0)

您的代码是完全正确的。 console.log不显示响应值的原因是因为它在处理响应之前正在运行。启动HTTP请求后,JavaScript会继续执行当前功能。

如果您想记录响应,则需要在响应处理程序中记录

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);
    });
  }    
}