1

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:

  1. Why the returned object is not of type Survey?
  2. Why my survey object cannot be displayed using expression?
  3. 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!

1

2 Answers 2

1

Since the value of survey is loaded asynchronously, its value is undefined at the beginning. You need to check it before trying to display its id property using ngIf:

<h1 *ngIf="survey">{{survey.id}}</h1>

or using the Elvis operator as suggestives by Eric in comment:

<h1>{{survey?.id}}</h1>
Sign up to request clarification or add additional context in comments.

Comments

1

As Eric mentioned use elvis operator or provide some dummy default for survey by property init.

private survery: Survey = {
    id: null,
    surveyType: ''
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.