I am trying to parse a simple JSON structure with arrays using Angular 2 typescript.
JSON structure:
[
{
"_id": {
"$oid": "594156331900006500e5f0f7"
},
"username": "John Smith",
"place": {
"name": "vvio",
"point": {
"type": "Point",
"coordinates": [
51.5044484,
-0.1056523
]
}
},
"from": "2017-05-01",
"to": "2017-05-30",
"availabilities": [
{
"date": "2017-05-01",
"timeFrom": "20:00",
"timeTo": "21:00"
},
{
"date": "2017-06-01",
"timeFrom": "20:00",
"timeTo": "21:00"
},
{
"date": "2017-06-19",
"timeFrom": "15:25",
"timeTo": "15:25"
},
{
"date": "2017-06-19",
"timeFrom": "15:59",
"timeTo": "15:59"
}
],
"sports": [
"Sport5",
"Sport2"
]
}
]
I create this class to map the JSON structure:
export class Checkin {
_id: Id;
username: string;
place :Place;
from: string;
to: string;
availabilities: Availability[];
sports: string[];
}
export class Id {
$oid: string;
}
export class Place {
name: string;
point: Point;
}
export class Point {
type: string;
coordinates: number[]; // number?
}
export class Availability {
date: string;
timeFrom: string;
timeTo: string;
}
Here is the service:
getCheckins(userName : string): Promise<Checkin[]> {
var options = new RequestOptions({
headers : new Headers({
'Accept': 'application/json;q=0.9,*/*;q=0.8',
'Content-Type':'application/json',
})
});
console.log("checkin ");
const url = `${this.checkinUrl}${userName}`;
return this.http.get(url)
.toPromise()
.then(response => {
let result = response.json();
console.log("response "+JSON.stringify(result));
return result as Checkin[]})
.catch(this.handleError);
}
Here is how I call the service:
getCheckins(): void {
console.log("called get checkin ");
this.userService.getCheckins("test@outlook.com").then(checkins => this.checkins = checkins);
console.log("printing checkins "+JSON.stringify(this.checkins));
for (let checkin of this.checkins) {
console.log("checkin "+checkin.username);
}
}
Here is the error I get (comes from the for loop):
AppComponent.html:1 ERROR TypeError: Cannot read property 'length' of undefined
at CheckinComponent.getCheckins (checkin.component.ts:46)
at CheckinComponent.ngOnInit (checkin.component.ts:34)
at checkAndUpdateDirectiveInline (provider.ts:275)
at checkAndUpdateNodeInline (view.ts:456)
at checkAndUpdateNode (view.ts:417)
at debugCheckAndUpdateNode (services.ts:235)
at debugCheckDirectivesFn (services.ts:294)
at Object.View_AppComponent_0.co [as updateDirectives] (AppComponent.html:3)
at Object.debugUpdateDirectives [as updateDirectives] (services.ts:273)
at checkAndUpdateView (view.ts:345)
It seems that I am not able to parse the json response into the json class..
Any help appreciated.