Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient mapping removes getters from target object

I am using HttpClient to get Json from the API and using the autoMapping of that HttpClient to map the json to the target object like this:

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

My problem is that my Person class contains getters like:

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

after httpClient.Post, i am getting a Person object that contains only the fields that returned from the json and not other properties and without my FullName getter.

I tried to use Object.Assign but it also not working...

What is the big deal of the httpClient.post generic method if its not doing map and only doing something like return JSON.parse(jsonResult)?

like image 323
Omtechguy Avatar asked Jan 28 '23 10:01

Omtechguy


2 Answers

The generic argument is only used for typing at compile time. You are informing the rest of your code that the object returned from the response will be compatible with Person. If the response doesn't include firstName or lastName properties your code still will not work properly unless you check the object shape yourself. If you want that object to have methods or other getters you will have to instantiate it yourself.

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

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

So you can have

class Person {
  constructor({ firstName, lastName }) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  get FullName() { return `${this.firstName} + ' ' ${this.lastName}`; }
}
like image 55
Explosion Pills Avatar answered Jan 31 '23 22:01

Explosion Pills


Object.assign() within the class constructor:

 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),
       );

Don't need to map each property youself:

this.firstName = firstName;
this.lastName = lastName;
like image 39
Yerkon Avatar answered Jan 31 '23 22:01

Yerkon