Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code:

public fetchResults(searchTerm: string): Observable<Array<SearchResult>> {
    let params = new HttpParams().set('searchTerm', searchTerm);

    return this.http
        .get<Array<SearchResult>>(this.apiUrl, { params: params })
        .map((results: SearchResult[]) => results.map((r: SearchResult) => new SearchResult(r)));
}

The problem lies in the fact that the API response is a JSON object which doesn't match the structure of my TypeScript class. Despite this mismatch, I want to utilize the properties defined within the TypeScript class.

Can anyone suggest a more efficient way to transform the array fetched from the API call into an array comprised of instances of SearchResult?

Below is the definition of the SearchResult object:

import { Name } from './name';

export class SearchResult {
    public id: string;
    public name: Name;
    public dateOfBirth: Date;
    public socialSecurityNumber: string;

    public get info(): string {
        let result: string = `${this.name}`;

        if (this.dateOfBirth)
            result += ` | ${this.dateOfBirth.toLocaleDateString()}`;

        return result;
    }

    constructor(data: SearchResult) {
        this.id = data.id;
        this.name = new Name(data.name);
        this.dateOfBirth = data.dateOfBirth? new Date(data.dateOfBirth) : undefined;
        this.socialSecurityNumber = data.socialSecurityNumber;
    }

    public toString(): string {
        return this.info;
    }
}

Answer №1

Utilizing a fantastic library for seamless mapping of JSON data to TypeScript objects. Take a look here!

The json-object-mapper relies on the reflect-metadata library, leveraging decorators for efficient serialization and deserialization of data.

Answer №2

To handle API responses in a more streamlined way, consider utilizing the TypeScript as operator for type casting to the ClientSearchResult interface.

import { Http, Response } from '@angular/http';

public search(searchString: string): Observable<ClientSearchResult[]> {
    const params = new HttpParams().set('searchString', searchString);
    return this.http.get(this.searchUrl, { params: params })
        .map((results: Response) => results.json() as ClientSearchResult[]);
}

This method necessitates using your model class as an interface:

interface ClientSearchResult {
  id: number;
  // etc
}

Answer №3

Recently, I have started utilizing a fantastic library (which was up-to-date when I began using it):

https://www.npmjs.com/package/class-transformer

This library excels at managing intricate scenarios involving nested classes and beyond.

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

Tips for adding multiple log groups in CloudFormation

Currently, I am working with a cloud formation stack that is a slightly modified version of the one provided by AWS at this link: https://aws.amazon.com/blogs/aws/cloudwatch-logs-subscription-consumer-elasticsearch-kibana-dashboards/?adbsc=startups_2015080 ...

The logic behind regular expressions

Currently working on building a web application with Angular 6 and I have a query: I'm in the process of developing a custom input component (specifically for text inputs) like so: @Component({ selector: 'input-text', templateUrl: &apos ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...

What is the technique for highlighting the exact data point on the XY am4chart when it is clicked?

I have been searching high and low for a solution to my problem but haven't had any luck. I am working with a traditional XY am4chart that has hundreds of data points in the line series. What I want is for the chart to display a vertical line (or some ...

What are the steps to create a properly structured JSON in Python?

I need to generate JSON queries for elastic search. This is the code I'm using to construct the query: search_doc = {} search_doc.update({"sort": [{"re_max": {"order": "desc"}}]}) search_doc.update({"from": 0}) search_doc.upda ...

Guide to crafting an optimized JSON file for your mobile application development initiative

Currently, I'm delving into JSON as I aim to create a local JSON file for my upcoming Flutter Mobile app Project. The layout plan for my mobile app involves displaying a list of genres on the home page. Upon clicking on a specific genre, the user wil ...

I encountered a problem encoding my JSON object into my WebClient's UploadString while specifying the Headers["Content-Type"] as "application/x-www-form-urlencoded"

I'm currently developing a web application using ASP.Net MVC 4, and I need to send a JSON object to a third-party API. According to the API documentation, the JSON data should be encoded with the content type set to application/x-www-form-urlencoded. ...

Converted requests from loopback to angular2 resulted in an error message, as the script's MIME type ('text/html') was determined to be non-executable

Currently, I have set up loopback as the backend API and angular2 as the frontend for my project. Loopback is serving my angular2 frontend without any issues. However, whenever I refresh a page, loopback seems to struggle with handling the URL because tha ...

Is it possible to retrieve messages from a service bus using an Angular app without relying on SignalR?

In our app, we are looking to post messages from our backend to an azure service bus in order to avoid waiting for a long process. Is it possible to do this directly from the front end, or do we need to implement a signalR solution with additional steps on ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Updating the value of the chosen drop down option upon selection

I currently have a Material UI dropdown menu implemented in my project. My goal is to use the selected option from the drop down menu for future search functionality. How can I utilize onChange() to store the selected option effectively? At the moment, I ...

Incorporating Angular for Dynamic Subdomains

Currently utilizing Angular for our project. We are in need of multi tenancy support for URLs containing sub domains. Our product is akin to Slack, where each tenant (client) possesses their own segregated database. Therefore, we desire for them to acces ...

Rails converts the database variable names and values

In my project, I am facing a challenge where I need to modify the name/value of a property in a class that is sourced from a database. This issue arises because there are two versions of an application accessing the same database, with the newer version ha ...

utilize the entire space designated for the <router-outlet> component

I am working with 3 components: <menu (setAnimal)='setAnimal($event)' ></menu> //PrincipalComponent <router-outlet (activate)='onActivate($event)'></router-outlet> <footer></footer> The red border ...

When using Google Maps, be sure to load it carefully as it may appear gray on the second attempt

After developing an Ionic 2 / Angular 2 App with integrated Google Maps, I encountered a problem. The second time the Google Maps loaded, it appeared completely gray. Despite trying various solutions found online such as triggering 'resize' event ...

React: Resolving the issue of "children" property not found in type "IntrinsicAttributes & Props"

Currently, I am attempting to retrieve data from an API and showcase it in a list of cards using React with TypeScript. As I am relatively new to working with React in Typescript, I am uncertain about how to resolve this error or if I have overlooked somet ...

Converting XML Schema into a JSON array list using Biztalk

Here is an example of a defined XML schema: <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"> <xs:element name="Root ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

Creating a Jersey REST server that returns a list of items in JSON format

There seems to be a discrepancy in the json structure of a returned list when the same code is executed on Tomcat versus Glassfish. @XmlRootElement public Class Person { private int personId; private String name; } @GET @Path("/persons") public R ...

Is there a way to transform a Map<Integer, Object> into JSON using GSON?

Hey there, I'm wondering if it's possible to convert a Map to JSON and back again using GSON. The object I'm working with has already been converted from JSON to an Object using GSON. The structure of the object I'm using is as follow ...