【问题标题】:Ionic/Angular - store content of an asynchronous http.get request in a variableIonic/Angular - 将异步 http.get 请求的内容存储在变量中
【发布时间】:2020-12-17 10:27:05
【问题描述】:

我尝试获取 URL 的内容。因为我处于异步模式,所以我使用 Promise。
使用 function(results) 我可以在 test123 变量中得到我想要的一切。但是,当我尝试将该结果存储在 test1234 变量中以在函数之外使用它时,它不起作用。更准确地说,test1234 的内容变得未定义..
我该怎么做才能使 test1234 变量充满该 http.get 的内容?

这里是sn-p:

     this.http.get(URL2).toPromise().then(
                function(results) {
                 var test123 = results['features'][0]['properties']['gid']; // works
                 this.test1234 = test123;
                 console.log(this.test1234); // doesn't work, it's "undefined"
                },
                //error function
                function(err) {
                  //handle error
                }
  );

感谢您的帮助。

【问题讨论】:

  • 看起来test123 确实未定义,我会检查这部分results['features'][0]['properties']['gid']。另外你为什么不使用 Observables?
  • 你为什么在 Angular 中使用 Promise?你怎么知道那东西有效?无论如何,使用箭头功能。

标签: angular asynchronous ionic-framework promise get


【解决方案1】:

如果你使用promise(你需要使用箭头函数)

this.http
  .get(URL2)
  .toPromise()
  .then(
    (results) => {
      this.test1234 = results['features'][0]['properties']['gid'];
    },
    (err) => {}
  );

但我建议你使用 observables

this.http.get(URL2).subscribe((results) => {
  this.test1234 = results['features'][0]['properties']['gid'];
});

【讨论】:

  • 好的,我忘记了使用窄函数。通过使用它确实有效。非常感谢!你能告诉我为什么使用 Observables 会更好吗?
  • 一个很好的论点是因为这正是 HttpClient 返回的内容。除此之外,RxJS 非常强大,解释一切都需要一段时间。另外,toPromise 即将被弃用indepth.dev/posts/1287/…
  • 好的,我知道了,谢谢你的精确,我会检查你的链接!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-02
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多