在angular中,为嵌套对象赋值

时间:2018-05-03 08:44:34

标签: angular typescript

我正在开发Angular 2应用程序。我有嵌套对象&sub-cuestions'的对象。我需要为它赋值,但是因为subQuestionId无法识别而得到错误。 subQuestionId是subQuestions的属性

错误

 TypeError: Cannot set property 'subQuestionId' of undefined

数据类

export class AnswerEntryDataModel{

consultationId:string;
responseId:string;
questionId:string;
answers:string[];
isPreDefineAnswer:boolean;
subQuestions:{
    subQuestionId:string;
    isPreDefineSubAnswer:boolean;
    subQuestionAnswers:string[];
 }
}

组件

export class myComponent implements OnInit {

private answerData = new AnswerEntryDataModel();
private answersList:string [] = []; 
private subQuestionAnswersList:string [] = []; 

 private assembleAnswer( responseId:string, questionId:string, subQuestionId:string, subQuestionInputType:string, subQuestionAnswersList:string[] ):AnswerEntryDataModel
{

  this.answerData.answers = [];

  this.answerData.consultationId = this.session.getItem('consultationId');
  this.answerData.responseId = responseId;
  this.answerData.questionId = questionId;

  if(subQuestionId!=null || subQuestionId!="undefined")
  {

    answerData.subQuestions.subQuestionId = subQuestionId; //throw error from here

    if(subQuestionInputType =="textbox"){  
      this.answerData.subQuestions.isPreDefineSubAnswer = false;
    }
    else {
      this.answerData.subQuestions.isPreDefineSubAnswer = true;
    }

    if(subQuestionAnswersList.length>0)
    {
      for(var itemIndex in subQuestionAnswersList)
      {
        this.answerData.subQuestions.subQuestionAnswers.push(subQuestionAnswersList[itemIndex]);
      }
    }

  }

  console.log("***** complete answer data ", this.answerData);

  return this.answerData;

}

1 个答案:

答案 0 :(得分:1)

subQuestions是尚未实例化的对象。

你可以像以下一样摆脱这个错误:

answerData.subQuestions = { subQuestionId: subQuestionId };