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

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

Using Python to extract information from a JSON response

After extensive searching, I have only managed to find half of the solution to my issue. When I received a JSON response, it looked like this: { "queryResponse": { "@last": 3, "@first": 0, "@count": 4, "@type": "ClientD ...

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

What is the best way to simulate a dynamoDB call using jest?

In a simple Handler, I have calls to getData defined in a separate file export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { let respData = await new DynamoDBClient().getData(123); return { status ...

Updating part of an object using TypeScript

I am looking to create a utility function that takes an instance and an object as input, and then updates the instance with the values from the provided object fields. Below is the code for the utility function: function updateEntity<T, K extends keyof ...

Sharing assets across different Angular applications is a powerful way to improve code

I am currently developing a series of small applications that will utilize common modules and shared assets. For guidance on how to structure the projects, refer to this answer: The organization of my project folders is as follows: -root --projects ---ap ...

Utilizing a loop to extract and display JSON data within a table

In the process of building a website using Laravel, I encounter a JSON response from the server that looks like the following: [{"id":1,"user_id":"1","patient_name":"kk","age":"44"," ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

What are the methods for showcasing data within a string?

I'm struggling to figure out how to display the column names from a JSON file. Currently, all the column names are being displayed in one column, and empty fields are showing up for some reason. How can I format it so that the column names are listed ...

Displaying fresh data from a JSON URL by clicking on a button and dynamically refreshing the view in

Apologies if this question has been asked before, but I couldn't locate it. I’m currently engaged in an Angular project where I’ve loaded an external JSON file using http. The data is presented through ngRepeat. When a button is clicked, I aim t ...

Retrieve a section of a JSON file in Python and save it into a new JSON file

I need to filter out specific data from a JSON file using a predefined list of keys and save it as a new JSON file. For example: { "211": { "year": "2020", "field": "chemistry" }, " ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Using JQuery Datatable plugin to bind data in ASP.NET MVC applications

Having trouble implementing the JQuery Datatable plugin in my ASP.NET MVC application. Despite receiving JSON data from the controller, the table is stuck displaying a "Loading..." message. Here is my controller code: public ActionResult GetCompanies(jQu ...

Throw a specific exception pointing to the location of invalid JSON data without cluttering your code with excessive try/catch

Dealing with a complex JSON object containing various settings can be challenging. Here's an example structure: { "configuration" : { "name": "<room name>", "players": {"min": 3, &quo ...

Data fetched by Next.js is failing to display on the web page

After writing a fetch command, I was able to see the data in the console.log but for some reason it is not showing up in the DOM. export default async function links(){ const res = await fetch('https://randomuser.me/api/'); const data = ...

The combination of Material UI and React Hook Form is encountering an issue with submitting disabled checkboxes

My current challenge involves ensuring that all fields are disabled while the form is submitting. I have successfully implemented this for text, selects, and radios, but I am facing difficulties with required checkboxes. I am working with nextjs typescrip ...

I encountered a problem when trying to set up ngx-Spinner version 8.0.3

I need help implementing a spinner loader in my app. I have followed the instructions provided at [ https://www.npmjs.com/package/ngx-spinner ] and successfully installed it. However, when trying to import and add it to "imports", I encountered the follow ...

The application rejected the application of styles from 'http://localhost:1234/node_modules/primeicons/primeicons.css' as the MIME type (text/html) was not compatible

Encountering an error when attempting to add the following styles in index.html within my Angular 6 application. Getting a refusal to apply the style from 'http://localhost:1234/node_modules/primeicons/primeicons.css' because its MIME type ...

Angular - Automatically filling in an empty input field upon dropdown selection

My goal is to create a DropdownBox that will automatically fill input fields based on the selected value. For example, selecting "Arnold" from the dropdown will populate another textbox with "Laptop". How can I accomplish this? { name:'Arnold', i ...