0

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.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + this.key).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 here
    console.log('called >> ', this.latLong)

    return this.latLong;

  });

  //this.latlong is undefined !
}

//if I call getCoords() here I get undefined too
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Folky.H
  • 1,164
  • 4
  • 15
  • 37

2 Answers2

2

If subscribe returns a Promise, return call, 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 = new Promise((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 here
      console.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));
guest271314
  • 1
  • 15
  • 104
  • 177
  • Tried that; however, it throws an error saying that '.then' does not exist on type Subscription – Folky.H May 14 '17 at 15:19
  • What does `.subscribe()` return? – guest271314 May 14 '17 at 15:26
  • `.subscribe()` is an observable that takes tree parameters `.subscribe(success, failure, complete)` – Folky.H May 14 '17 at 15:31
  • You can use `Promise` constructor to call `resolve()` within `success` or `reject` within `failure`, return the `Promise` constructor from call. See updated post – guest271314 May 14 '17 at 15:41
  • this one `return call.then(res => { console.log(res); return res })` replaced `undefined` by `__zone_symbol__state` which I don't know from where it came. For the last line `getCoords().then()` says that `property` then does not exists on type `void` – Folky.H May 14 '17 at 15:52
  • You need to include more details at Question. What is `__zone_symbol__state` ? Can you reproduce issue at plnkr https://plnkr.co? See https://stackoverflow.com/help/mcve – guest271314 May 14 '17 at 15:58
  • I, myself don't know it, I believe it came from `Promise` constructor – Folky.H May 14 '17 at 16:00
0

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.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135