【问题标题】:Get value outside the Class in javascript [duplicate]在javascript中获取类之外的值[重复]
【发布时间】:2020-03-23 23:08:00
【问题描述】:

我想使用 2 个 API 构建一个网站。我为每个 api 制作了 2 个单独的类。我需要在 getWeather() 和天气类之外获取“data.currently.icon”。我正在尝试范围之外的所有变量,getter&setter。我该如何解决?

class Weather {
  constructor() {
    this.getLocation();
    this.lat;
    this.lng;
    this.icon;
  } // end constructor

  getLocation() {
    navigator.geolocation.getCurrentPosition(
      this.myLocation.bind(this),
      this.errorLocation.bind(this)
    );
  }

  myLocation(result) {
    this.lat = result.coords.latitude;
    this.lng = result.coords.longitude;
    //console.log(this.lat);
    this.getWeather();
  }

  getWeather() {

    let url = `https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/15684c4ffc14f32fcd28af8aa81bc818/${this.lat},${this.lng}?units=si`
    fetch(url).then(response => {
      //get json 
      return response.json();
    }).then(data => {
      document.querySelector('#test').innerHTML = data.currently.summary;
      document.querySelector('#test2').innerHTML = data.currently.temperature + "deg";
      //data.currently.icon
    }).catch(err => {
      console.log(err);
    });
  };

  errorLocation(err) {
    console.log(err);
  }

} // end class Weather
let weather = new Weather();
console.log(icon);

【问题讨论】:

  • getWeather() 是异步的。即使您可以访问该变量,在您调用new Weather() 后它也不会立即可用,因为异步调用尚未返回。
  • myLocation()result 参数应该是什么?
  • @DiegoSaravia 结果是对象 GeolocationPosition

标签: javascript api bind weather-api


【解决方案1】:

你写//data.currently.icon的地方可以说

this.icon = data.currently.icon;
return Promise.resolve(this.icon);

最后一行将允许您执行以下操作:

let weather = new Weather();
weather.getWeather().then(icon => console.log(icon));

并且您必须在fetch(...) 之前添加return,以便getWeather() 返回一个Promise,从而允许在获取数据后执行then

【讨论】:

  • 无法读取未定义的属性“then”。
  • 是的,现在我想起来很有道理,getWeather() 没有返回 Promise,让我再考虑一下
  • 尝试在fetch(url) 之前添加return (并使用我的答案中的其余更改)
  • 现在只是“未定义”
  • 您确定data.currently.icon 中有值吗?如果您在then 中使用console.log,您应该能够在获取数据后看到它的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-11
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
相关资源
最近更新 更多