javascript - 使用 async 和 axios 制作天气应用
问题描述
我相当确定这是一个我不记得如何修复的细节,但我已经获得了从 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
成为 aHTMLCollection
而不是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();
推荐阅读
- arrays - 快速创建一个数组数组
- android - 如何使用 RecyclerView 显示沿滚动条移动的文本?
- angular - 无法在 Angular 4 测试中加载字体
- xml - 带有元素树的 Python XML:解析子节点上满足多个条件/条件的节点
- r - Rmarkdown YAML 中的引号和内联 R 代码
- java - 带有改造 2 的 JSON 或 POJO
- html - 如何在 wordpress 网站上将 3 个服务框居中
- neo4j - 如何在 Neo4j 中跨不同标签之间的整个数据集创建关系
- cluster-computing - 从 sge 中的 qsub 命令中排除特定节点
- reactjs - Chrome DevTools 不支持公共类字段的断点(第 3 阶段)?