【发布时间】:2016-03-19 21:23:04
【问题描述】:
我正在调查 Angular2 Http 客户端,但我不知道为什么我不能执行以下操作。
我阅读了以下 JSON 文件:
{
"id": 1,
"surveyType": "Type1"
}
进入:
export class Survey {
constructor(public id:number, public surveyType:string) {
}
}
使用 HTTP 客户端。
在我的服务中,我调用 HTTP GET:
getSurvey() {
return this.http
.get(this.surveyUrl)
.map((response:Response) => <Survey>response.json());
}
而在我的组件中我有:
survey:Survey;
ngOnInit() {
this.getSurvey();
}
getSurvey() {
this.surveyService.getSurvey()
.subscribe(
(survey:Survey) => {
this.survey = survey;
console.log(this.survey);
},
error => console.log(error)
);
}
我的模板只包含:
<h1>{{survey.id}}</h1>
执行代码时,总是出错。
TypeError: Cannot read property 'id' of undefined in [{{survey.id}} in SurveyComponent@0:4]
堆栈跟踪中的上下文变量读取:
context
SurveyComponent
survey
Object id: 1, surveyType: Type1
我也在控制台中看到了这个对象:
Object {id: 1, surveyType: "Type1"}
我的担忧:
- 为什么返回的对象不是 Survey 类型?
- 为什么我的调查对象无法使用表达式显示?
- 最后,我怎样才能让这样的例子工作? API 返回单个对象,而不是数组。
我正在使用 Angular2 Beta 11。
提前致谢!
【问题讨论】:
标签: angular