Skip to content Skip to sidebar Skip to footer

Javascript - Can't Get The Value Of The Function Outside Of It, Getting Undefined

I am willing to get the value of the function outside of it; however, I am getting undefined here is the below code: getCoords() { let call = this.http.get('https://maps.googleap

Solution 1:

If subscribe returns a Promise, returncall, chain .then() to get the value this.latLong returned from within .subscribe()

getCoords() {
  let url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' 
             + address + '&key=' + this.key;
  let call = newPromise((resolve, reject) => {
    this.http.get(url).subscribe(data => {

      let lat = data.json().results[0].geometry.location.lat;
      let long = data.json().results[0].geometry.location.lng;

      this.latLong = {
        "lat": lat,
        "long": long
      };

      //I can get it hereconsole.log('called >> ', this.latLong)

      resolve(this.latLong);

    });
  });

  return call.then(res => { console.log(res); return res })
  //this.latlong is undefined !
}

getCoords()
.then(data =>console.log(data))
.catch(err =>console.log(err));

Solution 2:

Sure, because http.get is async method so the callback function (subscribe) will call after the line this.latlong will call, so in that time this.latlong is undefined.

Post a Comment for "Javascript - Can't Get The Value Of The Function Outside Of It, Getting Undefined"