[英]How to convert data received from API to JSON format in angular 5
[英]API data won't convert to JSON format
在我的应用程序的先前版本中拥有 JSON 中的数据,但是(在 StackOverflow 社区的帮助下)重新设计了我如何调用我的 API 以修复各种其他中断错误。
这是我刚刚尝试过的。 我记录了“常规”output 以及将其转换为 JSON 的尝试。 非 json output 在我的控制台中显示为“{data: Array}”,而 JSON 未定义。
componentDidMount() {
axios
.get(
"API_KEY"
)
.then((res) => {
const data = res.data
const json = data.json
this.setState({ data, loading: false });
console.log(json);
console.log(data)
});
}
这是我的另一个尝试:
componentDidMount() {
axios.get("API_KEY").then((res) => {
const data = res.data;
this.setState({ data, loading: false });
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
});
}
非常感谢您的所有帮助和建议::)
我会建议使用 ES6 更好的语法。
const componentDidMount = async () => {
let { data } = await axios.get("API_KEY")
// Your data by default should be object or array.
// Regardless, both should worked fine.
console.log(data)
// In case it is just string and not undefined
if (data && typeof data !== 'object') {
data = JSON.parse(data)
}
this.setState({ data, loading: false })
}
否则,请在得到结果后首先尝试使用断点或 console.log。 如果结果未定义,则可能 promise 尚未解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.