0

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?

fabiomf
  • 205
  • 3
  • 8
  • are you able to see the data after the service is called in console ? `console.log(this.gifs)` ? – Niladri Oct 23 '17 at 08:06

1 Answers1

1

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.

Derek Brown
  • 4,232
  • 4
  • 27
  • 44
  • Thank you for the reply. I'm still having problems getting the url for the gif image. If anyone could help me, I'd appreciate it. https://developers.giphy.com/docs/ – fabiomf Oct 23 '17 at 00:52
  • @fabiomf can you be more specific about what is not working? – Derek Brown Oct 23 '17 at 00:56