angryip angryip - 1 month ago 4
TypeScript Question

Typcasting json to class angular 2

I have been following a few tutorials around the net, and have come to the conclusion that if my Angular 2 application calls a rest endpoint, I can automatically map the result to an interface or to a class I define. Hence, I am attempting to do the latter. Here is some sample json that I am working with:

{
"StudentResponse": {
"haveProblems": false,
"students": [
{
"id": "55",
"name": "Joel"
},
{
"id": "56",
"name": "Anderson"
}
]
}
}


Here are the two classes I am attempting to construct. First, this is my main response wrapper.

import {Students} from "./Students";

export class StudentResponse {

haveProblems: boolean;
students: Student[];

constructor(json: any) {
console.log("### we are in the main response constructor");
this.haveProblems = json.StudentResponse.haveProblems;
if(json.StudentResponse.students && this.haveProblems != true) {
this.students = json.StudentResponse.students.map((student) => new Student(student));
}
}
}


This is a child within the main response wrapper.

export class Student {

id: string;
name: string;

constructor(student: any) {
if (student) {
this.id = student.id;
this.name = student.name;
}
}
}


I am calling the mapping to this type in the following GET Rest call:

private getStudents(url: string): StudentResponse {
return this._http.get(url, getOptions())
.map(res => <StudentResponse>res.json())
.catch(this.handleError)
}


I have noticed that the console statement in my StudentResponse class is never invoked. However, If I add an anonymous function in the map method, I can parse the json and create a new StudentResponse manually. Obviously, I want to make this easier for myself, and let angular do it. I wish I still had the link to the article, but I am hoping someone else can chime in and point out the issues in my typecasting here.

Additional things tried with comments that did not work:

constructor(res: Response) {
console.log("### we are in the constructor");
let json = res.json();
...
}

// map the rest response
.map(res => new StudentResponse(res))

Answer

Posting my comment as an answer:

To call the constructor you need to change it to

.map(res => new StudentResponse(res.json())