What is the best way to assign JSON values to my class property?

I've been working on a weather application that showcases the current weather of 5 different cities. By clicking on each city, users can access a detailed view displaying the 5-day forecast for that particular location.

Currently, I have defined a weatherItem class as follows:

export class WeatherItem {
  city: string;
  description: string;
  temperature: number;
}

*I have implemented this method in my weatherService to retrieve the current weather information for the 5 cities:

fetchCurrent(){
    return Observable.forkJoin(
      this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Chicago&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
      (response) => response.json()),
     this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Dallas&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
       (response) => response.json()),
     this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Milwaukee&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
       (response) => response.json()),
     this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Seattle&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
       (response) => response.json()),
     this.http.get('http://api.openweathermap.org/data/2.5/weather?q=Washington&units=imperial&appid=f630449a4407b742703bf37d8e8c9057').map(
       (response) => response.json())
  );
  }

This is the function I call in my WeatherComponent which utilizes the fetchCurrent() method from the weatherService:

getWeather(): void {
   this.weatherService.fetchCurrent()
   .subscribe(data => this.weatherItems = data);
  }

The current weather data from openweathermap.org is successfully fetched, but the way it's displayed in my WeatherComponent is like this:

<ul class="weatherItems">
    <li *ngFor="let weatherItem of weatherItems" class="box" (click)="gotoDetail(weatherItem)">
      <div class="col-1">
        <h3>{{weatherItem.name}}</h3>
        <p class="info">{{weatherItem.weather[0].description}}</p>
      </div>
      <div class="col-2">
        <span class="temperature">{{weatherItem.main.temp}}° F</span>
      </div>
    </li>
  </ul>

I'm struggling with mapping the JSON data to my view correctly. For instance, I initially referred to the city using {{weatherItem.city}} when using mock data. However, now with the JSON data, I can only display it correctly by using {{weatherItem.name}} instead. Is there any way in Angular 2 to bind the "name" data from JSON to the weatherItem.city property?

Answer №1

To start, if your WeatherItem represents the model of your backend class, it should mirror the properties of the JSON object:

export class WeatherItem {
  constructor(weather: Weather,
              base: string,
              id: number,
              name: string,
              cod: number) {}
}

export class Weather {
    constructor(id: number,
                main: string,
                description: string,
                icon: string){}
}

Next, make sure to declare your weatherItems like this:

public weatherItems: Array<WeatherItem>; // or just weatherItem: Weather if your JSON returns a single object

You can also create a complete model with the rest of your JSON properties (main, wind, rain, etc), but only if you actually need them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue occurred when attempting to validate a JSON string with PHP's json_decode function

I encountered the following error: Notice: Trying to access a property of a non-object in action.php Even though the posted JSON has been validated by jsonLint.com. Here is the JSON string in question: [ { "eTGid": "1", "eTid": "34", "evra ...

Is it possible to create a channel list using the YouTube API if I am not the owner of the channel? I am not getting any errors, but nothing is showing up

I am currently working on creating a channel list and playlist of videos from a Music channel that I do not own. Here is the link to the channel: https://www.youtube.com/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ/featured. My goal is to extract data from this channe ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

Navigating with the Angular router leads to an unexpected destination: "mat-radio-group-0=true"

I'm facing an issue with a close button in my HTML template that triggers a close() function in the component: HTML template: <div> <label id="radio-group-label">Please specify: </label> <mat-radio-grou ...

"Efficient ways to calculate the total sum of an array of objects based on a specific property

I currently have a straightforward method that calculates the total sum of an object array based on one of the properties. const calculateSum = <T extends object, K extends keyof T>(array: T[], property : K) : number =>{ let total = 0; if ( ...

Traversing Nested JSON Objects in NodeJS: How to Remove Elements Conditionally

If I have the following object: { "schema": [ { "field": "name", "type": "String", "enabled": true }, { "field": "age", "type": "Int", "enabled": false }, { "field": "modelObj", "type": "object", "enabled": true, "stuff": [ { ...

Learn the process of inserting a JSON String into an Android spinner

My Json response is returning as a single object instead of an array. This object contains dynamic key-value pairs, like so: { "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "key5": "value5", "key6": "value ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

Submitting a form using jQuery and receiving data in JSON format

Utilizing the Jquery form plugin, I am sending my form via ajax. The PHP script on the server side processes the form data and provides a JSON string in this specific format: {"error":true,"message":"The username or email already exists. Please try agai ...

Retrieving nested JSON objects in Node.js using Express and Postgres through iterative queries

I've been experimenting with this code in Node.js using Postgres to retrieve a list of nested JSON objects like the one shown below: { "elements": [ { "name": "element 1", "description": "lorem ipsus", ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

Resolving Node.js email attachment problem by selecting a file using Postman form-data

Hello, I am currently experiencing difficulties with sending email attachments. Can you please advise me on how to send a file that I have selected from form-data in Postman? How do I specify the path of the file? //const Joi = require('joi'); c ...

Conceal the HTML element within a subscription

Currently, I am utilizing Angular and have a checkbox that I need to toggle visibility based on the response of an API call subscription. The issue lies in a delay when trying to hide the checkbox (as it is initially set to visible). My assumption is that ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

The JSON response from XHR begins with the word "for."

While examining a few Facebook XHR requests, I noticed that there is a cross-domain request with a JSON response that begins like this: for (;;); {/* JSON object */} Why does the response start with a for? I suspect it might be for security reasons. Can ...

Retrofit encounters a server issue with a 500 Internal Error

I'm facing an issue while trying to update a database record using the Retrofit library. The Postman works fine with the same data. GET request is also functioning properly, but when I try the PATCH operation, it returns an Error 500 Internal Server E ...

Choosing a value with an Ionic checkbox

Here's the coding template I'm working on: <ion-list > <ion-item> <ion-label>This month</ion-label> <ion-checkbox checked=true></ion-checkbox> </ion-item> ...

Retrieve data from an API and store it in a JSON array

My website is having an issue where it's fetching data from an API and displaying it in a table, but all the cells are returning undefined values. The data in the API is structured as an array with multiple datasets inside curly braces that I am unsu ...

Have you attempted to configure a JSON file to facilitate language translations?

I need some guidance on structuring my data.json file efficiently. Currently, it is set up as shown in the example below. The goal is to have a drop-down menu where users can select a language and then display 50 different pages with specific content. I wa ...