Search code examples
javascriptangularapitypescriptgiphy

Object from GIPHY API prints nothing


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)
        );

    }
}

If I write console.log(this.gifs) , it logs nothing.

But if I write console.log(gifs) from inside the arrow function, it prints the object I want.

What do I do?


Solution

  • 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.

    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.