The concept of "Mapping" another property and returning undefined using Angular's HttpClient in Setters and Getters

There seems to be an issue with the behavior of setters and getters that are setting or returning another public property on the object in TypeScript when retrieved using Angular's (v5) HttpClient.

Here is the code snippet:

export interface NamedEntity {
    id: number;
    name: string;
    priority?: number;
}

export Rule implements NamedEntity {
      ruleId: number;
      ruleName: string;

      get id(): number {
          return this.ruleId;
      }
      set id(id: number){
           this.ruleId = id;
      }
      get name(): string {
          return this.ruleName;
      }
      set name(name: string){
           this.ruleName = name;
      }
}

//Another class that implements NamedEntity similarly

I am fetching Rule objects through HttpClient:

 return http.get<Rule[]>("my url");

Upon subscribing to the Observable<Rule>, it appears that properties not using getters/setters display correctly both in the debugger and within angular templates. However, the getter/setter based properties show as undefined in the debugger and blank in the angular template.

My Angular project was created with Angular-CLI and my tsconfig.json has "es5" set as the target.

This issue likely arises from how HttpClient converts the data into the shape defined by the generated Rule interface in TypeScript. How can I ensure that the resulting objects from the HttpClient call are instances of the actual Rule class instead of just its implicit interface?

Answer №1

To better understand the situation, more code would be required. It seems that you may be expecting the http request to return a Rule object, but it actually returns data with properties defined by the Rule object. This means that the returned data does not include any of the object's getters, setters, or methods.

If your object is flat (without hierarchy), one approach could be:

let x = Object.assign(new Rule(), rule);

Here, rule represents the data obtained from the Http call.

The provided code creates a new Rule object with all its associated getters, setters, and methods, and then copies the data into it for further manipulation.

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

Error message: The function URL.createObjectURL is not recognized in this context | Issue with Antd charts

Currently, I am working on integrating charts from antd into my TypeScript application. Everything runs smoothly on localhost, but as soon as I push it to GitHub, one of the tests fails: FAIL src/App.test.tsx ● Test suite failed to run TypeError: ...

Display or conceal elements in Angular based on multiple conditions

Looking to develop a functionality where an array of objects can be shown or hidden based on specific filters. The desired output should be as follows: HTML CODE: Filter: <div (click)="filter(1)"> F1 </div> <di ...

Troubleshooting Shader Loading Issues in an Angular Application Utilizing Three.js

Check out this component: https://www.npmjs.com/package/app3d-three-template Here's the Plnkr link: https://plnkr.co/edit/bdkshJFzhwmLNdgO?preview The issue I'm facing is related to the fire Shader not displaying the correct color. Additionally ...

Issues arise when attempting to extract data from a data provider using JSON within the context of the Ionic framework

Hey there! I'm relatively new to the world of Angular and Ionic, and I've embarked on a project to create a pokedex app. My approach involves using a JSON file containing an array of "pocket monsters". However, my current challenge lies in extrac ...

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

Cannot execute loop

I'm currently working on creating a loop within my component that involves making server calls: getBeds() { this.patientService.getBeds(this.selectedWard).subscribe( result => { console.log(result); this.beds = result; this.getBedDet ...

Converting an array of entities from a server response into a separate object in Angular 6

I am currently working on transforming a response list into a different type of object. I have a HTTP call that returns Observable<Object1> and I am looking to convert it to {id: string, type: string} (more details below). getData(): Observable<O ...

Assistance for Angular 2 Style Guide within Atom: Feature Needed!

My manager uses Atom with a set of eight plugins specifically designed for Angular development. I have the same plugins installed on my system, but I seem to be missing a feature that he has. We're unsure which plugin or preference setting is required ...

Error message in Angular 8: Cannot be assigned to AsyncValidatorFn

I am currently working on implementing a custom validator function in a reactive form. Here is the code snippet: form.component.ts ... form = new FormGroup({ username: new FormControl('', [ Validators.required, ...

HowlerJS: Unauthorized Access - Error Code 401

Working with Angular 7, I have developed an application that consumes data from an API. I have successfully implemented CRUD functionalities using an http-interceptor that adds a token to each request. However, I encountered a 401 error when integrating Ho ...

What is the best way to set an ion-toggle to default to the "on

I'm currently working with an ion-toggle in Ionic 2. I want it to be set as default to on, however, using the checked attribute did not produce the desired result. <ion-toggle [(ngModel)]="ratingModel.contact" formControlName="contact" id="contact ...

Ways to verify if the output from translate.instant has been properly translated at least once

With ngx-translate, I have implemented the following function and my goal is interface IWidgetFilterValue = { label: string; value: string; } getSortedOptions(filterOptionsArr: IWidgetFilterValue[]): IWidgetFilterValue[] { const filterOptionsArrNew = ...

The correct way to type a generic React function component using TypeScript

When attempting to generalize the function component Element into a GenericElement component in TypeScript Playground, I encountered syntax issues that raised complaints from TypeScript. What is the correct method for typing a generic react function compo ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

"Upon the initial page load, the persistence of values in local storage using Next.js, React, and Recoil

Check out this code I have, const Layout: React.FC<LayoutProps> = ({ children }) => { const darkMode = useRecoilValue(darkModeAtom) console.log('darkMode: ', darkMode) return ( <div className={`max-w-6xl mx-au ...

Incorporate all photographs from a designated directory in the gallery into an Angular 6 PWA Application

Currently, I am developing a Progressive Web Application that requires me to showcase all images stored under a specific directory (for instance, all pictures saved in the "Downloads" folder on a mobile device) within a personalized grid view. I would lik ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...

Tips on triggering an Angular 2 method once a jQuery promise has been resolved

I am currently incorporating the Third Party Library called MarvinJS into my Angular5 Application. In order to successfully handle a MarvinJS promise, I need to execute the method this.sharedService.openMarvinModal(false);. However, upon executing this me ...

What is the process for switching views by tapping on a button?

Currently, I am working on a registration form that consists of 3 steps. I need to change the view of the form to another view when clicking the Next button. I have been attempting to achieve this in Angular 2 by using routing, but it seems to be replacin ...