We have a variety of Http calls to our services that return a collection of objects. In our angular application, typescript interprets these into the appropriate type if specified, for example Person:
export class Person{
public firstName: string;
public lastName: string;
public salutation: string;
}
Let's say I want to be able to easily build a greeting string for this user, but I want to be a good programmer and do it once instead of multiple places. So I create a getter that will retrieve it:
export class Person{
public firstName: string;
public lastName: string;
public salutation: string;
public get greeting(): string {
return salutation + " " + firstName + " " + lastName;
}
}
However, when typescript deserialized it, it is missing the prototype of the greeting property (it is set to undefined). I get that typescript is mapping the JSON object to the class it has, and any missing fields/properties do not exist on the mapped object (returning undefined if called). What's the best way to fix this?
As an example of how we are calling the service:
this.authHttp.post(this.url, user, params).then(
(res: Person) => {
console.log(res);
console.log(res.greeting);
}
);