Search code examples
angularasynchronousionic-frameworkpromiseget

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


I try to get the content of a URL. I use the Promise since I'm in an asynchronous mode.
With the function(results) I can get all I want in the test123 variable. But when I try to store that result in the test1234 variable to use it outside the function it does not work. To be more precise the content of test1234 becomes undefined..
How could I do to make the test1234 variable filled with the content of that 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.


Solution

  • If you use promises (you need to use arrow function)

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

    But I suggest you use observables

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