I am trying to cast my response from a http get call using httpclient and create an instance of a class I have created.
PROBLEM
The HttpClient doesnt seem to create a new instance of my class using the properties of its response object. Please help!
I have tried creating a class vs interface. Not sure what else i need to be doing here.
My Class
export class Escalation {
constructor(private NAME: string, private DESCRIPTION: string) { }
public get name() {
return this.NAME;
}
public set name(name: string) {
this.NAME = name;
}
public get description() {
return this.DESCRIPTION;
}
public set description(description: string) {
this.DESCRIPTION = description;
}
}
My Service
public getEscalation(escalationName) {
return this.http.get(`${this.globals.baseRestUrl}/companies/escalations/${escalationName}`);
}
My Component
public escalation: Escalation = new Escalation('', '');
this.companiesService.getEscalation(escalationName).subscribe(
(escalationResponse: Escalation) => this.escalation = {
...escalationResponse
}, (error: any) => {
console.log(error);
}
);
Expected Result
I was expecting my response to be casted to type Escalation (My class) upon api callback.
Actual Result
the api returns an object like so:
{
NAME: 'Escalation 1',
DESCRIPTION: 'This is a test description'
}
But eventually this.escalation returns undefined
I hope I explained it well. Please let me know if you need more information!
The (escalationResponse: Escalation)
line of code isn't really intended to cast the response from the HttpClient but rather to infer what type it is.
You may consider adjusting your code to this.escalation = new Escalation(escalationResponse.NAME, escalationResponse.DESCRIPTION)
I believe this.escalation = { ...escalationResponse }
is really only deconstructing the properties anyway.