我正在开发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;
}
答案 0 :(得分:1)
subQuestions
是尚未实例化的对象。
你可以像以下一样摆脱这个错误:
answerData.subQuestions = { subQuestionId: subQuestionId };