我相当确定这是一个我不记得如何解决的细节,但是我已经获得了从URL中提取数据的代码,但是我无法调用setResults()方法。我敢肯定有办法解决,但我不确定该怎么做。
class Test {
constructor() {
this.testResults = document.getElementsByClassName('test-results');
}
async run() {
console.log(new Date().toISOString(), '[Test]', 'Running the test');
// TODO: Make the API call and handle the results
const url = `http://api.openweathermap.org/data/2.5/weather?q=${query}&appid=25e989bd41e3e24ce13173d8126e0fd6&units=imperial`;
//Using the axios libary to call the data and log it.
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
console.log(data);
var results = data;
} catch (error) {
console.log(error);
}
};
getData(url);
}
setError(message) {
// TODO: Format the error
this.testResults.innerHTML = (message || '').toString();
}
setResults(results) {
results = responses()
this.testResults.innerHTML = (results || '').toString();
}
}
最佳答案
您未看到的错误可能与testResults
是HTMLCollection
而不是HTMLElement
有关。
因此,为了使setResults
方法正常工作,您需要对其进行调整。
在这里,我提供了一种可能的解决方案。
class Test {
testResults;
constructor() {
this.testResults = document.getElementsByClassName('test-results');
}
async run() {
console.log(new Date().toISOString(), '[Test]', 'Running the test');
// TODO: Make the API call and handle the results
const url = `http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=25e989bd41e3e24ce13173d8126e0fd6&units=imperial`;
//Using the axios libary to call the data and log it.
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
this.setResults(data);
} catch (error) {
console.log(error);
}
};
getData(url);
}
setError(message) {
// TODO: Format the error
this.testResults[0].innerHTML = (message || '').toString();
}
setResults(results) {
results = JSON.stringify(results);
for(let resultEl of this.testResults) {
resultEl.innerHTML = (results || '').toString();
}
// this.testResults[0].innerHTML = (results || '').toString();
}
}
let testObj = new Test();
testObj.run();
关于javascript - 使用async和axios制作天气应用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58296109/