Angular 2+: The art of creating an instance of a class using data retrieved from the backend

Within my Angular app, I have a Customer class and an ICustomer interface.

interface ICustomer { <-- obtained from backend
    id: number;
    name: string;
    address: string; 
    // additional properties
}

class Customer { <-- widely used in the Angular app
    // other fields
    constructor(public data: ICustomer) {};
    // other methods
    refresh() {
        // ... fetching customer data from the backend
    }
}

I am trying to create an instance of Customer with an object like {'id': 5} and call its 'refresh()' method. However, this results in a compile-time error due to the lack of implementation for all members of ICustomer.

One approach to overcome this is by adjusting ICustomer to include '?' after each member variable, such as:

interface ICustomer {
    id: number;
    name?: string;
    address?: string; 
    // more properties
}

After these modifications, {'id': 5} can technically be considered an instance of ICustomer.

Nevertheless, this solution feels somewhat unsatisfactory. Is there a more effective way to handle this issue?

Edit: While I agree with storing backend data in a 'data' field of type ICustomer, my query specifically pertains to the instantiation of the Customer class.

Answer №1

attempt {'ID': 5} as Customer

This method should produce the desired result.

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

When employing `queryParams` in Angular routing, the URL will automatically replace `%` with `%25`

When trying to use queryParams for navigation in Angular routing, I encountered an issue. <a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a> The d ...

The rendering of code is often disrupted when utilizing the keyword const

I've been working my way through the Angular2 tutorial called Tour of Heroes and everything has been going smoothly up until this point. At the link above, I've encountered a problem. The code on the left is what the tutorial recommends, but fo ...

Building a Custom Dropdown Select List with FormControlName and ControlValueAccessor in Angular 8

Does anyone have a working solution for creating a Material dropdown wrapper (mat-select dropdown) that can be used with formControlName? If so, could you please share a Stackblitz demo of your implementation? Here are the requirements: Should work seam ...

Is there a way to beautify a non-serializable Python object without using eval?

response = self.es.search(**parameters) print(json.dumps(response), indent=2, sort_keys=True)) TypeError: Object of type ObjectApiResponse is not JSON serializable If I str(object), I can see it as a string with no formatting: print(json.dumps(str(respons ...

My Python program is receiving a "400 Bad Request" error from the Strawpoll.me API, yet the API functions properly when accessed through the terminal

I recently wrote a Python program to generate strawpolls using the API provided by strawpoll.me. You can find more information about the API here. import aiohttp import asyncio async def createPoll(): question = "Is this thing on?" options = ["Ye ...

access JSON data file in R with a u' prefix

I have a text file with JSON data, but it includes the u'' prefix in its content. {u'ItemId': u'100052388', u'RealTimePlaying': u'570.3', ....} Is there a way to import this file into R? I have also uplo ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

Differentiating Views for a Single URL in Angular 6: Enhancing Progressive Web Apps

Below is the content from my app-router.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DheaderComponent } from './dheader/dheader. ...

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...

Should I avoid incorporating jQuery into Angular applications?

I'm curious about whether it's best to steer clear of using jQuery in an Angular application, considering the idea that only one entity should be handling DOM manipulation. Has anyone encountered situations where jQuery was the necessary quick fi ...

Exploring Typescript: Enhancing the functionality of `export = Joi.Root`

I've noticed that the types for @hapi/joi appear to be outdated - some configuration parameters mentioned in the official documentation are missing from the types. To address this, I am attempting to enhance the existing types. node_modules/@types/ha ...

The CanLoad guard does not permit access to the root route

My original idea was to create a project where the main website, located at "/", would only be loaded lazily after the user logs in. const routes: Routes = [ { path: '', canLoad: [AuthGuard], loadChildren: './home/home.module#HomeModule&a ...

Utilizing Django Ajax to specify a URL with two dynamic URL paths (e.g. <str: 'first_variable'>/<str: 'second_variable'>/fetch/)

I've created a Django ajax template to retrieve all the Players from a players model: <body> <h1>List of Players:</h1> <ul id="display-data"> </ul> </body> <script> $(document).ready(fun ...

The JSON array (such as [4,5,6]) cannot be deserialized into the specified type due to its requirement for a JSON object (like {"title":"content"}) in order to deserialize accurately

Hello, I am attempting to retrieve data from an API and then perform some LINQ operations on it, but I am having trouble displaying it properly. The dynamic type works well, but I'm unable to use LINQ with it. The API I am using can be found at Here ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

I encountered an issue with the proxy configuration while working with Npm and Angular, specifically after installing and then uninstalling

Ever since I removed Fiddler, I've been encountering issues with using Angular and npm, specifically related to proxy errors. When attempting an http call with Angular, I receive the following error: [HPM] Error occurred while trying to proxy reque ...

Converting a JSON array into a Java map

I am currently working on a project that involves receiving a JSON response from my API using entities and DTO. Here is an example of the response structure: return XXXResponseDTO .builder() .codeTypeList(commonCodeDetailL ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

The issue persists in VSCode where the closing brackets are not being automatically added despite

Recently, I've noticed that my vscode editor is failing to automatically add closing brackets/parenthesis as it should. This issue only started happening recently. I'm curious if anyone else out there has encountered this problem with their globa ...