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)?
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}`; }
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With