angular - 错误:无法读取 null 的属性“find”
问题描述
我的应用程序有问题。我已将我的问题表格分成 2 个单独的组件,一个用于单答案,一个用于多答案。
我收到一条错误消息
“错误:无法读取属性 'find' of null”
从第二个问题导航到第三个问题时。该"answers"
变量为空,似乎答案没有从问题组件传递到测验组件,也没有被推送到答案数组。
这似乎影响了解释文本的显示,导航无法导航到第二个问题并且评分不起作用。请你看看我的 Stackblitz:https ://stackblitz.com/edit/angular-10-quiz-app并帮助解决这个问题。谢谢你。
问题组件:
<ng-content></ng-content>
<form [formGroup]="formGroup">
<question-single-answer [question]="question"></question-single-answer>
<question-multiple-answer [question]="question"></question-multiple-answer>
</form>
在测验组件中给出错误的代码:
checkIfAnsweredCorrectly(): void {
if (this.question) {
const correctAnswerFound = this.answers.find((answer) => {
return this.question.options &&
this.question.options[answer] &&
this.question.options[answer]['selected'] &&
this.question.options[answer]['correct'];
});
const answers = this.isAnswered() ? this.answers.map((answer) => answer + 1) : [];
this.quizService.userAnswers.push(this.isAnswered() ? answers : this.answers);
this.addUpScores(answers, correctAnswerFound);
}
}
解决方案
在您提供的 StackBlitz URL 中,您似乎answers
在一开始就为变量分配了一个空的数字数组。
后来,this.answers
在函数和函数null
等多个地方。之后,很可能会在您收到此错误的地方调用该函数。advanceToNextQuestion
advanceToPreviousQuestion
checkIfAnsweredCorrectly
请再次验证您的逻辑。这是一个逻辑错误。
推荐阅读
- ssl - 如何在 Go 中缓存/重用 TLS 连接
- opencv - OpenCV 和 libav 用于 Amazon EC2 AMI 上的编解码器
- javascript - 是否有以语言环境字符串格式获取 UTC 日期的功能?
- shell - 如果没有按预期进行则很简单
- emacs - 如何在 Eshell 中突出显示某些单词?
- javascript - 如何根据显示的值更改徽章颜色
- php - 当在 Woocommerce 单页中无法购买产品时显示自定义消息
- java - 如何根据GPA对数组列表进行升序排序?arraylist 包含一个对象数组。(爪哇)
- javascript - 使用 Reduce 方法在 JavaScript 中反转字符串
- python - Python:当变量被类方法调用时,对象变量存在“NameError”