我想使用2个API建立一个网站。我为每个api制作了2个单独的类。我需要在getWeather()和Weather类之外获取“ data.currently.icon”。我正在尝试范围之外的所有变量,getters&setters。我该如何解决?
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);
你写//data.currently.icon
的地方可以说
this.icon = data.currently.icon;
return Promise.resolve(this.icon);
最后一行将允许您执行以下操作:
let weather = new Weather();
weather.getWeather().then(icon => console.log(icon));
并且您必须在return
之前添加fetch(...)
,以便getWeather()返回一个Promise,这反过来又允许在获取数据后执行then
。