我正在使用angular 2从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),它什么也不记录。

但是,如果我从箭头函数内部编写console.log(gifs),它将打印出我想要的对象。

我该怎么办?

最佳答案

您所描述的是比赛条件。 .subscribe()中的arrow函数是一个回调函数,这意味着它在HTTP get返回之后执行。但是,此功能是非阻塞的,因此其余代码将继续执行。因此,当您尝试this.gifs时可能未设置console.log

为了解决这个问题,您应该使用某种反应性数据类型(例如Promises或RxJS),以便仅在this.gifs设置后才能获取它的值。

关于javascript - GIPHY API中的对象不打印任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46880371/

10-10 01:19