无法访问 Typescript 中的嵌套 JSON 对象键:值
2020-12-16
295
当我将 TypeScript 对象分配给嵌套 JSON 对象 (main) 的键 (temp) 时:
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 is not an object
这是 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
}
所以我不太确定为什么会抛出这个异常。 我正在使用 Ionic v3。
1个回答
this.weather.getWeather("Dublin").subscribe(data => {
this.weatherToday = data.main.temp;
});
<p>{{weatherToday}}</p>
Ravi Ashara
2021-01-01