Search code examples
jsonangularhttpstring-interpolation

String interpolating a property of returned json in Angular


I'm trying to build a test questionnaire from a json response. In console I get errors of 'Cannot read property 'Title' of undefined' because it seems like it wants to string interpolate before I get the response.

My code looks like this so far:

component.ts:

export class QuestionComponent implements OnInit {
  jsonQuestionnaire: Questionnaire;

  constructor(private http: HttpClient) { }

  ngOnInit() {
    console.log(this.jsonQuestionnaire);
    // Make the HTTP request:
    this.http.get('/assets/equestion.json').subscribe(data =>  {
    //   // Read the result field from the JSON response.
      this.jsonQuestionnaire = data as Questionnaire;
      console.log(this.jsonQuestionnaire);
      console.log(this.jsonQuestionnaire.Title);
      }
    );
  }
}

questionnaire.model.ts:

export interface Questionnaire {
  GuestName: string;
  QuestionnaireClose: boolean;
  QuestionnaireCompleted: boolean;
  Sections: Section[];
  Title: string;
  WelcomeText: string;
}

export interface Section {
  SectionName: string;
  SectionId: number;
  Questions: Question[];
}

export interface Question {
  AnswerReqired: boolean;
  Answers: Answer[];
  QuestionID: number;
  QuestionName: string;
  QuestionType: string;
}

export interface Answer {
  AnswerID: number;
  AnswerName: string;
}

and my html:

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <h1>{{jsonQuestionnaire.Title}}</h1>
      <p>{{jsonQuestionnaire.WelcomeText}}</p>
      <div *ngFor="let section of jsonQuestionnaire.Sections; let j = index">
        <br>
        <p>{{section[j].SectionName}}</p>
      </div>

    </div>
  </div>
</div>

Could anyone point me in the right direction what I got to fix? If I log all the properties I get as a response I do that without a problem. So how to delay the string interpolation?

Best regards, Aghi


Solution

  • You can either add a *ngIf to your HTML:

    <div class="container">
      <div class="row" *ngIf="jsonQuestionnaire">
        <div class="col-xs-12">
          <h1>{{jsonQuestionnaire.Title}}</h1>
          <p>{{jsonQuestionnaire.WelcomeText}}</p>
          <div *ngFor="let section of jsonQuestionnaire.Sections; let j = index">
            <br>
            <p>{{section[j].SectionName}}</p>
          </div>
        </div>
      </div>
    </div>
    

    or add an safe navigation operator to you *ngFor:

    <div class="container">
      <div class="row">
        <div class="col-xs-12">
          <h1>{{jsonQuestionnaire.Title}}</h1>
          <p>{{jsonQuestionnaire.WelcomeText}}</p>
          <div *ngFor="let section of jsonQuestionnaire?.Sections; let j = index">
            <br>
            <p>{{section[j].SectionName}}</p>
          </div>
        </div>
      </div>
    </div>