我在构建表单时出错(提交日期快到了,可能是因为恐慌(
我在我的谷歌DevConsole上收到了这个错误,但页面加载完全符合我的要求。
`ERROR TypeError: Cannot read property 'answers' of undefined
at Object.eval [as updateDirectives] (QuestionsComponent.html:20)
我的html
<div class="custom-control custom-radio" *ngFor="let question of question.answers">
<input type="radio" class="custom-control-input" id="answers" name="groupOfRadios">
<label class="custom-control-label" for="answers">{{question.body}}</label>
</div>
我的TS
export class QuestionsComponent implements OnInit {
//define variables to use
private question : {
id: number;
body: string;
answers: {
id: number;
body: string;
}[]
}
constructor(private router: Router, private http: HttpClient, private quest: QuestionService) { }
ngOnInit() {
this.quest.getQuestion().subscribe(
data=> {
this.question = {
id: data.question.id,
body: data.question.body,
answers: data.question.answers
}
}
)
}
}
我想通过服务器发送json-resp和数据来加载一个问题。
答案是一系列id和bodies属于该问题。
对不起,谢谢你的耐心。
祝福!
在标记中,首先检查question
是否接收到数据,然后对其进行迭代。使用安全属性访问器-question?
。
<div class="custom-control custom-radio" *ngFor="let question of question?.answers">
<input type="radio" class="custom-control-input" id="answers" name="groupOfRadios">
<label class="custom-control-label" for="answers">{{question.body}}</label>
</div>
或者只是用答案的空数组初始化变量
private question: {
id: number;
body: string;
answers: {
id: number;
body: string;
}[]
} = {
id: 0,
body: null,
answers: []
}
您可以使用*ngIf="question"
,因此只有在question
对象中有数据后,此HTML部分才会呈现,直到HTTP调用完成。
<div *ngIf="question" class="custom-control custom-radio" *ngFor="let question of question.answers">
<input type="radio" class="custom-control-input" id="answers" name="groupOfRadios">
<label class="custom-control-label" for="answers">{{question.body}}</label>
</div>