【发布时间】: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 获取数据需要时间,所以如果你想获取这些数据,你应该等待并异步执行。