I’ve been trying to map a HTTP response (from my REST API, that are returning a JSON) into a custom model that i made in my Angular project. First i call this function to get the results from my rest API, casting it as a DHEntity (it's my model)
getProjectData(idDH): Observable<DHEntity>{
return this.http.get<DHEntity>(`${environment.apiUrl}/dh/${idDH}`, {observe: 'response'})
.pipe(map(data => data.body));
}
The json i get from the call (so the body of my response) is correct. Then, i call another method to process the information
getData(): void {
const idDH = +this.route.snapshot.paramMap.get('idDH');
if (idDH){
this.dh1Service.getProjectData(idDH).pipe( map(
res => {this.DHlist = res}
));
}
I've also tried as suggested to subscribe directly, since the model is identical to my endpoint results
getData(): void {
const idDH = +this.route.snapshot.paramMap.get('idDH');
if (idDH){
this.dh1Service.getProjectData(idDH).subscribe(
res => {this.DHlist = res});
}
In addition to those two, I've tried also several other ways (including the use of "new" statement, with a defined constructor) trying to return a correct entity: none of them is working. Everytime i get an undefined value, no matter what i do. Seems like Angular is not able to cast to the specific type. My model is made through several classes as follows (i omit constructors for brevity reasons):
export class DHEntity{
idDH: number;
dhinfo: DHInfo;
dhdata: DHData[];
}
export class DHInfo {
name: string;
targetYear: number;
description: string;
decisions: DHDecisionDefinition[];
}
export class DHData {
dec1: number;
dec2: number;
eval: number;
}
export class DHDecisionDefinition {
id: number;
description: string;
targetY1: string;
targetY2: string;
targetY3: string;
comments: string;
}
Is there a reason why i cannot map the values correctly? What am i doing wrong? Here one example of the JSON i get from my endpoint: Link
.map
functions to verify that the shape of the data is as expected?. Also keep in mind that you are running those requests asynchronously, so even if everything is working as intended,this.DHList
will not be set to a defined value until some indeterminate time in the future after having calledgetData
.