API中的对象不打印任何内容

API中的对象不打印任何内容

本文介绍了GIPHY API中的对象不打印任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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()中的arrow函数是一个回调函数,这意味着它在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中的对象不打印任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 03:23