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

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

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

这是片段:

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

感谢您的帮助。

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

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