在本教程getting-started-with-angular-2-step-by-step-6-sumption-real-data-with-http/之后,我正在尝试使用 angualrio 从 json 文件中读取数组。
但是我收到了错误
ERROR TypeError: undefined is not a function
错误发生在这一行
return response.json().map(this.toEvent)
由于http response
已更新,上面的行与教程不同。reponse.json()
现在回来Body.json()
为了简化和模仿我的问题,我创建了一个 json 数组 x 如下
let x = [{
eventId:132510417453240,
title:"Discover",
description:"do",
startDateTime:1512316800000,
endDateTime:1512320400000,
url:null
}]
然后使用this.toEvent(x[0])
下面调用函数的行
private toEvent(r:any): Event{
let event = <Event>({
eventId: Number.parseInt(r.eventId),
title: r.title,
description: r.description,
startDateTime: Number.parseInt(r.startDateTime),
endDateTime: Number.parseInt(r.endDateTime),
url: r.url
});
console.log('Parsed event:', event);
return event;
}
然而我最终得到了错误ERROR TypeError: this.toEvent is not a function
更新(响应@Yonexbat)toEvent 与我调用它的范围相同。两个函数在类中紧随其后,如下所示
private toEvent(r:any): Event{
let event = <Event>({
eventId: Number.parseInt(r.eventId),
title: r.title,
description: r.description,
startDateTime: Number.parseInt(r.startDateTime),
endDateTime: Number.parseInt(r.endDateTime),
url: r.url
});
console.log('Parsed event:', event);
return event;
}
private mapEvents(response:Response): Event[]{
// The response of the API has a results
// property with the actual results
console.log(response)
console.log(response.json()[1])
console.log(response.text()[1])
let events : Event[] = [];
events = response.json()
//return events
return response.json().map((x) => this.toEvent(x))
}