[英]Using async and axios to make a weather app
I'm fairly certain it's a detail that I can't remember how to fix, but I've gotten the code to pull the data from the URL, but I can't call the setResults() method.我相当确定这是一个我不记得如何修复的细节,但我已经获得了从 URL 中提取数据的代码,但我无法调用 setResults() 方法。 I'm sure there is a way around it but I'm unsure how to do it.
我确定有办法解决它,但我不确定该怎么做。
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();
}
}
The bug that you did not see is probably related to testResults
being a HTMLCollection
rather than HTMLElement
.您没有看到的错误可能与
testResults
是HTMLCollection
而不是HTMLElement
有关。 So in order to make the setResults
method to work properly you need to adjust it.因此,为了使
setResults
方法正常工作,您需要对其进行调整。 Here I'm providing a possible solution.在这里,我提供了一个可能的解决方案。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.