I'm experiencing some strange behavior regarding setters & getters that set/return another public property on the object in TypeScript when retrieved from Angular's (v5) HttpClient
.
Here are the important constructs:
export interface NamedEntity {
id: number;
name: string;
priority?: number;
}
export Rule implements NamedEntity {
ruleId: number;
ruleName: string;
//..other properties
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 in the same way
I'm retrieving Rule
objects using the HttpClient
as such:
return http.get<Rule[]>("my url");
When subscribing to that Observable<Rule>
I've found that all the properties that are not getters/setters display without an issue both in my debugger and within my angular templates. However, the setter/getter based properties always display undefined in the debugger, and blank on my angular template.
My angular project was set up with Angular-CLI and my tsconfig.json has the target set to "es5".
This is most likely because the HttpClient
casts the data into the shape that is the Rule
interface that is generated by TypeScript. How would I have the resulting objects from the HttpClient
call be instances of the concrete Rule
class rather it's implicit interface?
I would need to see more code to be sure ... but I would guess that you are expecting your http request to return a Rule object. It does not. Instead it returns its data with properties as defined by the Rule object. Meaning it does not have any of the object's getters, setters, or methods.
If your object is general flat (no hierarchy) you could do something like this:
x = Object.assign(new Rule(), rule);
Where rule
is the value back from the Http call.
This code creates a new Rule object (that then has the getters, setters, and methods) and copies the data into it.