Javascript - 无法获取函数的值,未定义

时间:2017-05-14 15:02:41

标签: javascript

我愿意在它之外获得函数的价值;但是,我得到undefined这里是以下代码:

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

2 个答案:

答案 0 :(得分:2)

如果订阅返回Promisereturn call,则链.then()以获取this.latLong .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));

答案 1 :(得分:0)

当然,因为http.get是异步方式,所以回调函数(subscribe)会在行this.latlong将调用后调用,所以在那个时间{ {1}}是this.latlong