简体   繁体   中英

Cannot access nested JSON Object key : value in Typescript

When I assign a TypeScript object to a key (temp) of a nested JSON object (main):

weatherToday : any;

getTheWeather(city : String)
  {
    console.log("HOME.TS: Getting the weather...");
    this.weather.getWeather("Dublin").subscribe( data => {
      this.weatherToday = data.main.temp;

    });

  }

And then output the weatherToday object in home.html:

<p>{{weatherToday}}</p>

The output is as expected: 284.73

However when I try to assign the Typescript to the overall parent JSON object:

this.weatherToday = data;

And attempt to then output the same as above by object.object.value syntax in my home.html:

 <p>{{weatherToday.main.temp}}</p>

I get a exception:

undefined is not an object

This is the JSON structure:

{
  "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
}

So I am not quite sure as to why this exception is thrown. I am using Ionic v3.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM