首页 > 解决方案 > 无法访问嵌套的 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。

标签: javascriptangulartypescript

解决方案


this.weather.getWeather("Dublin").subscribe(data => {
      this.weatherToday = data.main.temp;

    });
 <p>{{weatherToday}}</p>

推荐阅读