问题描述
我正在使用 angular 2 从 GIPHY API 获取一些数据.
I'm using angular 2 to get some data from GIPHY API.
export class ListaGifsComponent {
gifs : Object[] = [];
urlBase = "http://api.giphy.com/v1/gifs/search?q=";
termoPesquisado = "ryan+gosling";
key = "O8RhkTXfiSPmSCHosPAnhO70pdnHUiWn";
constructor(http: Http){
http
.get(this.urlBase + this.termoPesquisado +
"&api_key=" + this.key + "&limit=10")
.map(res => res.json())
.subscribe(gifs =>
this.gifs = gifs['data'],
erro => console.log(erro)
);
}
}
如果我写 console.log(this.gifs) ,它什么都不记录.
If I write console.log(this.gifs) , it logs nothing.
但是如果我从箭头函数内部编写 console.log(gifs) ,它会打印我想要的对象.
But if I write console.log(gifs) from inside the arrow function, it prints the object I want.
我该怎么办?
推荐答案
您所描述的是竞争条件..subscribe()
中的箭头函数是一个回调函数,意味着它在 HTTP get 返回后执行.但是,此函数是非阻塞的,因此您的其余代码将继续执行.因此,当您尝试 console.log
它时,可能不会设置 this.gifs
.
What you are describing is a race condition. The arrow function inside .subscribe()
is a callback function, meaning it is executed after the HTTP get returns. However, this function is non-blocking, so the rest of your code continues to execute. Thus, this.gifs
may not be set when you try to console.log
it.
为了解决这个问题,你应该使用一些响应式数据类型(比如 Promises 或 RxJS),这样你才能在 this.gifs
被设置后获取它的值.
To remedy this, you should use some reactive data type (like Promises or RxJS) so that you can get the value of this.gifs
only after it has been set.
这篇关于来自 GIPHY API 的对象不打印任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!