简体   繁体   English

Ionic/Angular - 将异步 http.get 请求的内容存储在变量中

[英]Ionic/Angular - store content of an asynchronous http.get request in a variable

I try to get the content of a URL.我尝试获取 URL 的内容。 I use the Promise since I'm in an asynchronous mode.我使用 Promise 因为我处于异步模式。
With the function(results) I can get all I want in the test123 variable.使用函数(结果) ,我可以在test123变量中得到我想要的一切。 But when I try to store that result in the test1234 variable to use it outside the function it does not work.但是,当我尝试将该结果存储在test1234变量中以在 function 之外使用它时,它不起作用。 To be more precise the content of test1234 becomes undefined..更准确地说, test1234的内容变得未定义..
How could I do to make the test1234 variable filled with the content of that http.get?我该怎么做才能使 test1234 变量充满 http.get 的内容?

Here is the snippet:这是片段:

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

Thanks for the help.谢谢您的帮助。

If you use promises (you need to use arrow function)如果你使用promises(你需要使用箭头函数)

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

But I suggest you use observables但我建议你使用 observables

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM