Angular HttpClient mapping causes the removal of getters from the target object

Utilizing the HttpClient to fetch Json data from an API, I am utilizing the autoMapping feature of the HttpClient to map the json response to a specified object in this manner:

this.httpClient.post<Person>(url, body, { headers: headers, params: httpParams }).retry(ConfigurationService.apiHttpRetries)

The issue arises with my Person class as it includes getters such as:

get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }

Following httpClient.Post, the resulting Person object only contains the fields returned from the json and does not include other properties or the FullName getter.

I attempted using Object.Assign but that did not resolve the issue...

What is the underlying functionality of the httpClient.post generic method if it does not perform mapping and simply returns JSON.parse(jsonResult)?

Answer №1

Using the generic argument serves the purpose of providing type information during compilation. By specifying that the object returned from the response will align with the Person structure, you are ensuring compatibility. However, if the response lacks essential properties such as firstName or lastName, your code may not function correctly unless you validate the object structure manually. If you wish for the object to include methods or additional getters, you will need to create an instance yourself.

interface PersonResponse {
  firstName: string;
  lastName: string;
}

this.httpClient.post<Person>(url, body, headers).pipe(
  retry(ConfigurationService.apiHttpRetries),
  map(personProperties => new Person(personProperties),
);

As illustrated in the following example:

class Person {
  constructor({ firstName, lastName }) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
}

Answer №2

Using Object.assign() in the constructor of a class:

class Person {
     firstName: string;
     lastName: string;;
         constructor(data: Object|Person) {
            Object.assign(this,data);
         }
      get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
    }

    ...

        this.httpClient.post<Person>(url, body, headers).pipe(
              retry(ConfigurationService.apiHttpRetries),
              map(personProperties => new Person(personProperties),
       );

Avoid manually mapping each property:

this.firstName = firstName;
this.lastName = lastName;

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

Explore the Attribute and generate a Text-Node using the Renderer

Given the advice against directly accessing the DOM in Angular for various platforms, I am trying to figure out how to achieve the following using Renderer: a) Store the offsetLeft value of $event.target in a variable called left. b) Create a text node wi ...

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

Obtaining the interface for a Typegoose class model

I am currently exploring how to create an abstraction for Mongo model functions and looking into ways to reuse the model interface from a typegoose class. My goal is to have a function like this: import CountryModel, { Country } from '../../models/ ...

In order to address the issue of displaying a 404 error in In-Memory Angular,

I have watched all the videos regarding the In-memory web API and diligently followed all the steps and instructions. However, I am still encountering a 404 Error. Please inform me if I missed something or made an error. I have attempted to troubleshoot an ...

A new interface property type that is customized based on the type property that is passed in

My dilemma lies in a generic interface with a field depending on the passed type. I'm exploring the possibility of having another field that can accept any type from the passed type. For instance: interface sampleObject { name: fullName age: n ...

Using ngFor to iterate over a list of items in Angular and displaying them conditionally using ng

In the process of creating a template, I am faced with this challenge: <ul> <li *ngFor='let link of links'> <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container& ...

Struggling with Angular 5 Facebook authentication and attempting to successfully navigate to the main landing page

I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redi ...

"Embracing the Power of Font Awesome 5 in Angular 5

After using the font-awesome npm package (which is Font Awesome 4.7 version), I decided to upgrade to Font Awesome 5. In order to make this transition, I installed the following packages: "@fortawesome/angular-fontawesome": "^0.1.1", "@fortawesome/fontawe ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

ConcatMap in RxJS processes only the last item in the queue

Currently, I am implementing NGRX with RXJS. Within the effects layer, I am utilizing a concatMap to organize my requests in a queue fashion. However, once the latest request is finished, I aim to execute the most recent item added to the queue instead of ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

Retrieving the previous and current URL in Angular 8

Need help setting variables prevUrl and currentUrl in Angular 8 by fetching previous and current URLs. The scenario involves two components - StudentComponent and HelloComponent. When transitioning from HelloComponent to StudentComponent, I face an issue. ...

Searching for values within an array of objects by iterating through nested arrays to apply a filter

Having trouble returning the testcaseid from an array to this.filteredArray Able to fetch header value and all values of the array when the search word is empty. Seeking assistance with iterating through the testcaseid and header on the search input fiel ...

Passing parameters in React classes is a crucial aspect of creating

Within a project I am currently working on, there is a const defined for the page header which takes in parameters and utilizes the information: interface UserProps { user?: { name: string, image: string }, loading?: boolean, error?: E ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

A guide on eliminating repetitions from an array of objects by utilizing the spread operator

I am working with an object array that has a unique key called "id": var test = [ {id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""}, {id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""}, {id: ...

What is the process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

Filling MatTables using asynchronous rows and promises

Is there a way to asynchronously populate the rows of a MatTable with data from a collection of objects? I have a list containing each object's URL and I want to fill in the data as it loads, even if the rows are initially empty. This is my approach: ...