我的代码有一些问题。我正在使用开放天气 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));
}
Console Error:
TypeError: Cannot read property '0' of undefined
at UI.paint (ui.js:16)
at app.js:15
如果我通过描述属性在weather.js 文件中进行console.log 调用,它会正确回答我,但是当我调用ui.js 时,它会给出此错误。
这不仅适用于该属性,也适用于其他属性,我尝试调用国家属性并说它尚未设置。怎么解决?有人可以帮助我吗?
最佳答案
您可以将 api 调用的结果作为参数传递给 paint
方法,因为 Weather
类没有 weather
属性:
paint(data) {
this.location.textContent = data.name;
this.desc.textContent = data.weather[0].description;
}
function getWeather() {
weather
.getWeather()
.then(results => {
ui.paint(results);
})
.catch(err => console.log(err));
}
还要确保您的 api 响应实际上有 weather
prop,它是一个数组。
关于javascript - 当我尝试使用 json 获取 API 返回值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039804/