首页 > 解决方案 > 错误:无法读取 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);
    }
  }

标签: angular

解决方案


在您提供的 StackBlitz URL 中,您似乎answers在一开始就为变量分配了一个空的数字数组。

后来,this.answers在函数和函数null等多个地方。之后,很可能会在您收到此错误的地方调用该函数。advanceToNextQuestionadvanceToPreviousQuestioncheckIfAnsweredCorrectly

请再次验证您的逻辑。这是一个逻辑错误。


推荐阅读