I'm testing out writing a simple application in Angular2 to display the weather of a city. I've created a service to retrieve JSON data from OpenWeatherMap when a user types in a city and submits a form. Inside my service, I have:
getDummyWeather() {
return {"weather":{"main":"nice and sunny!"}};
}
I have the data stored as a JSON object called weather
in my component. I figured that the call inside my template to get main's string would be {{weather.weather.main}}
but then I get errors stating that the value main
cannot be retrieved from undefined. Obviously, it's undefined until I submit the form. When I submit the form, nothing happens. So then I tried {{weather.main}}
and I do not receive any errors, but I don't get any data back either. If I stringify the JSON, I get the full JSON string to display on form submit. Using {{weather}}
displays [Object object] on form submit.
How do I get data from a JSON object to display in my template in Angular2?
If the weather isn't available until you submit the form, then you shouldn't try displaying it until you know it's there:
<div *ngIf="weather.weather">{{ weather.weather.main }}</div>
If you really want to display it even if weather.weather is undefined, then you can use the safe navigation operator (also known as Elvis operator ) ?.
:
{{ weather.weather?.main }}
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.