Convert the JSON response from an http.get request into an instance of a TypeScript Model

One question still lingers in my mind: How can I convert the JSON response from an HTTP.get request into a Typescript object instance?

Let's establish the context:

CLASS =====================
export interface IMyClass {
  myClassId: number;
  myClassName: string;
  myClassDescription: string;
}

export class MyClass implements IMyClass {
  public myClassId: number;
  public myClassName: string;
  public myClassDescription: string;

  constructor(
    myClassId: number;
    myClassName: string;
    myClassDescription: string;
  ) {
    this.myClassId = myClassId
    this.myClassName = myClassName
    this.myClassDescription = myClassName    
  }
}


SERVICE===============
  public getMyClassById(id: number): Observable<MyClass> {
    return this.http.get<MyClass>(`${this.apiEndpoint}/myClassId?myClassID=${id}`)
  }

I'm exploring ways to achieve this without utilizing the complete constructor, as my actual Model consists of approximately 12 properties. I have attempted using pipe => mapping the response as MyClass but it didn't yield the desired results.

Answer №1

Trying to find a way to achieve this task without relying on the complete constructor method,

If you're searching for a deserialization (or hydration) library, I suggest checking out https://github.com/mobxjs/serializr. It's great for TypeScript projects 🌹

My perspective

I personally lean towards manually assigning values, even though it requires more code. This approach helps avoid unexpected bugs caused by "magic" processes.

Answer №2

One way to streamline your code is by consolidating everything in the constructor:

export interface IMyClass {
    myClassId: number;
    myClassName: string;
    myClassDescription: string;
}

export class MyClass implements IMyClass {

    constructor(
        public myClassId: number,
        public myClassName: string,
        public myClassDescription: string
    ) {

    }
}

When using the constructor, you only need to use the 'public' keyword for accessibility.

The presence of a semicolon in the constructor may have been unintentional and could be a mistake from copying and pasting code snippets.

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

Issue encountered with NextJS where the post request utilizing Bcrypt is not being recognized

In the process of developing a basic login feature using nextJS, I have successfully managed to save new usernames and encrypted passwords from the registration page. The login functionality is intended to be similar, but requires comparing the password st ...

Unsuccessful in assigning values to variable in Angular

The issue here is straightforward. After retrieving the latitude and longitude values from the browser, the correct values are printed. However, when trying to pass these values to the view by storing them in a variable, the variable ends up returning null ...

Loading columns and data dynamically into an Angular 2 table

I am working on an HTML page where I need to create a dynamic table. The columns for this table are fetched from the server and stored in a component variable using the type any[]. The data in the table is also dynamic, meaning that during programming, I d ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

"encountering a TypeScript error stating 'context.$implicit' is not a

I am currently working on a class setup that includes: import { ClassAsset } from './class-asset'; export class Class { ClassId:string; ClassName:string; Assets:ClassAsset[]; GetAssetsString():string{ var str:string; ...

Displaying components conditionally within an Angular child router outlet based on certain criteria

Trying to dynamically render components in the router-outlet based on the user's role is my current challenge. Imagine a DashboardComponent with a nested router-outlet. The component rendered in the child router-outlet should vary depending on the us ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

When creating a form group within another form group, ensure that formGroup is passed a FormGroup instance

I have created a form for adding users, which includes fields to input their birthdate. this.userFG = this.formBuilder.group({ name: [""], family: [""], birthDate: this.formBuilder.group({ day: [""], month: [""], year: [""] }) }); Wh ...

The instanceof function provides an erroneous response when verifying a valid condition

SCENARIO // debugging Discord applications import { Client } from 'discord.js'; export class Debugger { constructor(public client: Client) { console.log(client instanceof Client); // outputs false } } // main.ts import { Client ...

Is there another method to activate a button dynamically if the Router Link Active is not functioning in the given scenario?

Snippet of HTML code <div class="card-header"> <h5>Refill by date</h5> <div class="card-header-right"> <nav class="navbar bg-faded "> <ul class="nav navbar-nav"> <li class="nav-item" routerLinkA ...

Exploring methods to modify the Discord scopes in the upcoming Auth v5 update

image description placeholder I'm trying to modify the scope, remove the email and include guilds in my project. I searched for a solution but couldn't find one that worked. Can anyone help me figure out how to change the scopes? I attempted to ...

Tips for including an element at the start while creating a map()

enum StatusEnum { accepted = "AC", rejected = "RJ", } const select = (Object.keys(StatusEnum) as Array<keyof typeof StatusEnum>).map((x) => ({ value: x, name: x + "_random", })) /** * Console.log(select) * [ ...

Updating to Angular 2's latest release, rc5

Using forms provided in rc5 has been a challenge for me, as updating to that version is difficult. I attempted to follow a tutorial at but it was not compatible with rc3. Below is my boot.ts file: import { bootstrap } from '@angular/platform-browse ...

How to vertically align radio buttons with varying label lengths using Angular and Bootstrap 4?

Is there a way to properly align radio buttons with variable length labels? When each label has a different length, the radio buttons appear misaligned. How can this be fixed? <div class="row"> <div class="form-check form-check-inline" *ngFor="l ...

How to programmatically toggle an Angular Material slide toggle

Can anyone provide guidance on how to programmatically toggle the toggle() function in the code below? template <mat-slide-toggle color="primary" (change)="updateFunc($event)"></mat-slide-toggle> ts updateFunc(e) { // perform checks for a ...

In the scenario where I have a nested readonly array within an object, what is the best way to duplicate that object and transform the array to allow for mutations (such as inserting into Akita)?

Suppose I have the following TypeScript interface: interface Member { readonly id: number; readonly name: string; readonly email: string; groups: <ReadonlyArray>Group } interface Group { readonly id: number; readonly name: string; ...

Retrieve the key value pairs exclusively when utilizing the find method on a JSON array in JavaScript

To extract a value from a JSON array, I am utilizing the find method in this manner: let actualElm = this.initialData.find(elm => { if (elm.identifiant == this.actualId) { return elm.country; } }); An issue with using find is that it returns t ...

Angular 12 is throwing an error due to the undefined @Input property

The issue presents a simple problem to comprehend yet proves challenging to resolve. There are 2 key components involved: CustomerComponent (Parent) InvoiceComponent (Child) Currently, I'm passing customer details using <admin-invoice-form [custo ...

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

Exploring the capabilities of observables in mapping nested dynamic object keys, specifically focusing on manipulating data within angular-calendar events

Perhaps utilizing something like map<T,R> would be a better approach than my current method. I am hoping to receive some advice on how to resolve this issue. Currently, no events are being mapped due to incorrect mapping resulting in an incorrect pat ...