javascript - 无法访问嵌套的 JSON 对象键:Typescript 中的值
问题描述
当我将 TypeScript 对象分配给嵌套 JSON 对象(主)的键(临时)时:
weatherToday : any;
getTheWeather(city : String)
{
console.log("HOME.TS: Getting the weather...");
this.weather.getWeather("Dublin").subscribe( data => {
this.weatherToday = data.main.temp;
});
}
然后在 home.html 中输出 weatherToday 对象:
<p>{{weatherToday}}</p>
输出如预期:284.73
但是,当我尝试将 Typescript 分配给整个父 JSON 对象时:
this.weatherToday = data;
然后尝试在我的 home.html 中通过 object.object.value 语法输出与上面相同的内容:
<p>{{weatherToday.main.temp}}</p>
我得到一个例外:
undefined 不是对象
这是 JSON 结构:
{
"coord": {
"lon": -121.94,
"lat": 37.7
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 284.73,
"feels_like": 282.68,
"temp_min": 283.71,
"temp_max": 286.48,
"pressure": 1025,
"humidity": 62
},
"visibility": 10000,
"wind": {
"speed": 1.2,
"deg": 63
},
"clouds": {
"all": 1
},
"dt": 1608145061,
"sys": {
"type": 1,
"id": 4446,
"country": "US",
"sunrise": 1608131813,
"sunset": 1608166239
},
"timezone": -28800,
"id": 5344157,
"name": "Dublin",
"cod": 200
}
所以我不太确定为什么会抛出这个异常。我正在使用离子 v3。
解决方案
this.weather.getWeather("Dublin").subscribe(data => {
this.weatherToday = data.main.temp;
});
<p>{{weatherToday}}</p>
推荐阅读
- python - 根据条件组合熊猫数据框?
- sql-server - SQL 如何旋转和聚合另一列?
- css - 颜色变量只能单独工作,不能分组
- windows - xcopy 0 文件已复制
- webpack - 使用 WebPack 复制整个文件夹文件和子文件夹
- android-studio - 在 Android Studio 上运行项目时出错
- c++ - 在 Visual Studio 中运行用 C++ 编写的 oracle db 客户端时出现错误 32104
- jenkins - java.lang.NoSuchMethodError:在步骤中找不到这样的 DSL 方法“pollScm”(Jenkins 脚本化管道)
- android - 通用图像加载器加载半个网址
- qt - 为什么 QT 中的 CreateFile 不起作用,我怎样才能把它作为 QLocalSocket 或类似的