I am investigating Angular2 Http Client but I can't find out why I cannot do the below.
I read the following JSON file:
{
"id": 1,
"surveyType": "Type1"
}
into:
export class Survey {
constructor(public id:number, public surveyType:string) {
}
}
using HTTP Client.
In my service I call HTTP GET:
getSurvey() {
return this.http
.get(this.surveyUrl)
.map((response:Response) => <Survey>response.json());
}
Whereas in my component I have:
survey:Survey;
ngOnInit() {
this.getSurvey();
}
getSurvey() {
this.surveyService.getSurvey()
.subscribe(
(survey:Survey) => {
this.survey = survey;
console.log(this.survey);
},
error => console.log(error)
);
}
My template contains only:
<h1>{{survey.id}}</h1>
When executing the code, I always get errors.
TypeError: Cannot read property 'id' of undefined in [{{survey.id}} in SurveyComponent@0:4]
The context variable in stack trace reads:
context
SurveyComponent
survey
Object id: 1, surveyType: Type1
Also in console I see the object:
Object {id: 1, surveyType: "Type1"}
My concerns:
- Why the returned object is not of type Survey?
- Why my survey object cannot be displayed using expression?
- Finally, how can I get such an example working? The API returns single object, not an array.
I am using Angular2 Beta 11.
Thanks in advance!