【问题标题】:Object from GIPHY API prints nothing来自 GIPHY API 的对象不打印任何内容
【发布时间】:2018-04-03 11:18:20
【问题描述】:

我正在使用 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),它会打印出我想要的对象。

我该怎么办?

【问题讨论】:

  • 在控制台调用服务后能看到数据吗? console.log(this.gifs)?

标签: javascript angular api typescript giphy


【解决方案1】:

您所描述的是一种竞争条件。 .subscribe()里面的箭头函数是一个回调函数,意思是在HTTP get返回后执行。但是,此函数是非阻塞的,因此您的其余代码将继续执行。因此,当您尝试console.log 时,可能不会设置this.gifs

要解决这个问题,你应该使用一些响应式数据类型(如 Promises 或 RxJS),以便只有在设置 this.gifs 后才能获取它的值。

【讨论】:

  • 感谢您的回复。我在获取 gif 图像的 url 时仍然遇到问题。如果有人可以帮助我,我将不胜感激。 developers.giphy.com/docs
  • @fabiomf 你能更具体地说明什么不起作用吗?
猜你喜欢
  • 2020-12-30
  • 1970-01-01
  • 2019-05-26
  • 2021-02-13
  • 1970-01-01
  • 2020-05-18
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多