我在构建表单时遇到了一个错误(提交日期几乎要到了,也许是因为很恐慌)。
我在我的Google 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,而正文属于该问题。
对不起,谢谢您的耐心等候。
最良好的祝愿!
答案 0 :(得分:1)
在标记中,首先检查您的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: []
}
答案 1 :(得分:0)
您可以使用*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>