【发布时间】:2019-11-26 06:18:09
【问题描述】:
我的代码有一些问题。我正在使用开放天气 API 来创建这个应用程序。我可以轻松地获取 weather.js 文件中的值并移至 UI。只有它有一些值在控制台中以错误响应。遵循代码和错误。
文件weather.js
class Weather {
constructor(city, state) {
this.apiKey = "xxxxxxxxxxxx";
this.city = city;
this.state = state;
}
// Fetch weather from API
async getWeather() {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${this.city},${this.state}&APPID=${this.apiKey}`
);
const responseData = await response.json();
return responseData;
}
// Change weather location
changeLocation(city) {
this.city = city;
this.state = state;
}
}
文件 ui.js
class UI {
constructor() {
this.location = document.getElementById("w-location");
this.desc = document.getElementById("w-desc");
this.string = document.getElementById("w-string");
this.details = document.getElementById("w-details");
this.icon = document.getElementById("w-icon");
this.humidity = document.getElementById("w-humidity");
this.feelsLike = document.getElementById("w-feels-like");
this.dewpoint = document.getElementById("w-dewpoint");
this.wind = document.getElementById("w-wind");
}
paint() {
this.location.textContent = weather.name;
this.desc.textContent = weather.weather[0].description;
}
}
文件 app.js
// Init Weather Class
const weather = new Weather("rio de janeiro");
const ui = new UI();
// Get weather on DOM load
document.addEventListener("DOMContentLoaded", getWeather);
//weather.changeLocation("los angeles");
function getWeather() {
weather
.getWeather()
.then(results => {
ui.paint();
})
.catch(err => console.log(err));
}
控制台错误:
TypeError: 无法读取未定义的属性“0”
在 UI.paint (ui.js:16)
在 app.js:15
如果我通过 description 属性在 weather.js 文件中调用 console.log,它会正确回答我,但是当我调用 ui.js 时会出现此错误。
这不仅仅是这个属性,还有其他属性,我试图调用国家属性并说它没有设置。怎么解决?有人可以帮我吗?
【问题讨论】:
-
看来
paint()中的weather.name;等可能是指该文件顶部的const weather = new Weather("rio de janeiro");,但它不在sn-p 中,对吗?您需要将结果从getWeather()传递给ui.paint()。
标签: javascript json async-await