3

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?

3
  • [Object, object] is displayed when angular2 tries to interpolate an object. Run your variable through JSON.stringify() to convert your json object to a string. Then try to interpolate that value into the view. This should help you debug what is actually happening in your view. Commented Mar 10, 2016 at 15:38
  • The issue is with nested json objects. I am now able to get values from JSON like {"weather":"Nice and sunny"} by using {{weather.weather}}. I cannot get JSON from the sample JSON in my question above because of the nesting. Commented Mar 10, 2016 at 16:10
  • 1
    In case Google leads to this site when searching for debugging json variables. {{variable | json}} is the answer Commented Apr 2, 2017 at 15:26

1 Answer 1

5

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 }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.