我正在尝试使用Angular 2打字稿解析一个简单的JSON结构。
JSON结构:
[
{
"_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"
]
}
]
我创建这个类来映射JSON结构:
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;
}
这是服务:
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);
}
以下是我致电服务的方式:
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);
}
}
这是我得到的错误(来自for循环):
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)
似乎我无法将json响应解析为json类..
任何帮助表示赞赏。