Javascript - 无法获取函数外部的值,变得未定义

标签 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

最佳答案

如果订阅返回一个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));

关于Javascript - 无法获取函数外部的值,变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965421/

相关文章:

javascript - ./src/index.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/

javascript - 我可以使用什么代码使视频/动画/声音剪辑在我的网站上的特定时间后播放? Javascript 能做到这一点吗?

javascript - 有没有办法动态访问我的 Github Pages 服务器上托管的文件和文件夹?

javascript - 执行 ajax 调用时从 jquery for 循环中断返回错误

javascript - Typeahead 从 url json 值获取数据不起作用

javascript - react 导航,无法将标题传递给标题

javascript - 根据用户输入重定向

javascript - 弃用警告 : moment construction falls back to js Date when I use moment. js 获取当前日期

javascript - 如何调试 Node.js 应用程序?

javascript - 如何将变量添加到 setTimeout 名称?