Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal?

Below is my AJAX request:

public fetchSingle = (keys: any[]): Observable<Medal> => {
        return this._http.get(this.actionUrl + this.getKeyURL(keys))
            .map((response: Response) => response.json() as Medal )
            .catch(this.handleError);
}

This is how my medal model looks like:

    export interface Medal {
        medalNumber: number;
        awardingOrganization: string;
        dateAwarded: Date;
    }

And here is where I encounter the issue with the string conversion:

this._medalService.fetchSingle(this.ids).subscribe(
      (medal: Medal) => {
        console.log(typeof(medal.dateAwarded)); // <-- returning string and not Date
      },
      error => console.log(error);
      });

Answer №1

Explaining this concept can be a bit challenging:

Date is considered a class, meaning that objects of type Date must be created using a constructor function. In simple terms, you need to instantiate a class with new Date(...).

The Response.json method specifically returns an object in JSON format, which does not include an instance of any class, but rather key-value pairs.

To tackle this issue, you'll have to manually convert the data retrieved from .json() into an appropriate object structure. Below is one way to achieve this:

public getSingle = (keys: any[]): Observable<Badge> => {
        return this._http.get(this.actionUrl + this.getKeysUrl(keys))
            .map(r => r.json())
            .map(v => <Badge>{
              badgeNumber: v.badgeNumber,
              authorizationLevel: v.authorizationLevel,
              endOfValidity: new Date(v.endOfValidity)
              // It's recommended to use ISO-8601 format for dates
             })
            //There are alternative methods for mapping as well
            .catch(this.handleError);
}

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

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

Issues arise with Typescript Intellisense in Visual Studio Code causing it to stop functioning

I'm currently exploring the world of building desktop applications using Electron and Typescript. After selecting Visual Studio Code as my IDE, everything was going smoothly and I managed to successfully load a sample HTML file into Electron. However ...

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

Converting unique data sets from a JSON response into a CSV file

I have been working on a Python script to interact with the IPStack API. I am currently facing an issue when trying to write JSON output to a CSV file. In the next step of this project, I will need to send multiple IP addresses iteratively. My current roa ...

Confirm that a specific value exists within an enumerated set

I am currently using Angular 13.3.9 and typescript 4.6.4. My main objective is to determine if a value is referencing an enum. Below is the code snippet: export enum HttpFunctionalErrorCodes { ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND', USER_ ...

Creating separate template reference variables for items in an *ngFor loop in Angular can be achieved by using the

I have a question about setting template reference variables for buttons with different attributes when rendering them using *ngFor in Angular. Specifically, I want to set the reference variable as #button1, #button2, and so on for each button, but also ne ...

Utilizing Nginx with Angular2 for a seamless PathLocationStrategy implementation in html5

Angular2 is a single-page site, so all URL requests need to be redirected to index.html using Nginx. Below is the Nginx server block configuration: server { listen 8901; server_name my_server_ip; root /projects/my_site/dist; location /.+& ...

The Angular frontend application with proxy configuration is sending requests to the incorrect backend URL

My application is using Angular 11.0.6 as the front end, deployed on IIS and configured for mywebsite.com (port 80). The backend consists of a dotnet core web API deployed on IIS and configured for my.server.ip.address:190. Both the front end and back end ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

The JavaScript code runs first before retrieving any information from the server

When it comes to validating coupons on Stripe, the process needs to be done on the server side rather than the client side. I've tackled this by writing some code for validation, but I'm facing challenges with synchronizing the AJAX/JSON response ...

Generate a configuration file that allows for the reading and storage of modifications

Is there a way to create a configuration file (JSON) on the local file system using JavaScript where I can write and modify data without losing it when the application is restarted? Any suggestions or solutions for this problem? Thank you for your assista ...

Refresh Material-Ui's Selection Options

Is there a way to properly re-render the <option> </option> inside a Material UI select component? My goal is to transfer data from one object array to another using the Material UI select feature. {transferData.map(data => ( <option ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

Leveraging MySql inner join for displaying information in a visually appealing Google pie chart

I am working on displaying data using a Google pie chart, and I need to utilize two tables for this task. The tables are named authentication and agentdetails, both containing a column called "agentlogin". Agentdetails holds all the agent data, while authe ...

angularjs currency conversion tool

Is it possible to choose only 3-4 currency values from a drop-down list, where the selected value will determine the base URL for fetching JSON data? For instance, if I select USD as the first value, the JSON data should be retrieved from . ...

Utilizing JSON format, handling special characters, and storing data in a database

My friend approached me with a question and although I wanted to offer immediate help, I realized that seeking advice from others may provide better solutions. Situation: Imagine there is a Form that includes a RichText feature: DHTMLX RichText (). This R ...

Unable to simulate axios instance in a Typescript environment

After reading through this particular article, I decided to attempt writing a unit test while simulating Axios (with Typescript). Incorporating an Axios instance to define the baseUrl. // src/infrastructure/axios-firebase.ts import axios from 'axios ...

Ways to retrieve a specific attribute within a detailed JSON reply

I have implemented cloud code in ParseServer - Back4app, which utilizes node.js to send a request for Football API. The axios request returned the following result: { "result": { "get": "teams", "param ...