【问题标题】:How can I save http get response object in angular 6如何在角度 6 中保存 http 获取响应对象
【发布时间】:2019-02-06 19:05:57
【问题描述】:

我是 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));,这是预期的,但是分配不起作用。

非常感谢!

【问题讨论】:

  • 在订阅中记录 this.data,它是未定义的,因为您在 api 响应到达之前记录了数据。
  • http请求是一个异步操作。请求得到响应后,数据将被保存。
  • 这个命令是异步的'this.http.get(this.url).subscribe(response => this.data = response);'和setTimeout一样。您试图在订阅事件触发之前控制数据
  • 我可以用另一种方法来同步实现同样的事情吗?
  • 同步是什么意思?从 API 获取数据需要时间,所以如果你想获取这些数据,你应该等待并异步执行。

标签: json angular http-get


【解决方案1】:

您的代码完全正确。 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);
    });
  }    
}

【讨论】:

  • 好的,我知道 subscribe() 是异步的,有没有其他方法可以同步实现?
  • @obrassard 我不知道。 async/await 有可能会很接近,但我建议你不要打扰。 Web 请求本质上是异步的,您应该努力适应它们。你提到你是新人,我理解学习是多么烦人和令人沮丧——但从长远来看,它会对你有很大帮助。
  • 在响应处理程序中,我如何访问接收到的 json 对象的每个属性?这是控制台中的结果:{name: "The Weeknd", mbid: "c8b03190-306c-4120-bb0b-6f2ebfc06ea9", url: ...} 但是当我尝试获取 response.name 例如它是未定义的
  • @obrassard 没有自己运行代码,很难猜出原因。但是,我认为这可能是打字的问题,所以我会查看angular.io/guide/http#type-checking-the-response。由于您没有告诉 Angular 响应的结构(通过为它创建一个类),它可能不知道如何将响应解析为一个对象并作为字符串离开 - 因此输出到控制台作为字符串和 @ 987654327@ 未定义
  • 如果我创建一个类,我是否必须包含响应 json 对象的每个属性和数组?我可以只添加对我的项目重要的一项吗?
【解决方案2】:

您正在执行异步 HTTP 调用。所以你需要在订阅中添加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);
    });
  }

【讨论】:

  • 我明白了,在响应处理程序中,您知道我如何访问收到的 json 对象的每个属性吗?这是控制台中的结果:{name: "The Weeknd", mbid: "c8b03190-306c-4120-bb0b-6f2ebfc06ea9", url: ...} 但是当我尝试获取response.name 例如它是未定义的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
相关资源
最近更新 更多