开发者问题收集

Angular - 未捕获的 TypeError:无法读取未定义的属性“totalQuestions”

2020-06-21
156

我尝试将测验属性组合在一起作为 quizMetadata 对象,然后使用对象,但出现此错误:“错误:未捕获(在承诺中):TypeError:无法读取未定义的属性‘totalQuestions’”

export class ResultsComponent implements OnInit {
  quizData: Quiz = QUIZ_DATA;
  quizMetadata: {
    totalQuestions: number;
    correctAnswersCount$: Observable<number>;
    percentage: number;
    completionTime: number;
  };

...
constructor(private quizService: QuizService) {
  this.quizMetadata.totalQuestions = this.quizService.numberOfQuestions();
  ...
}
3个回答

您可能想要 订阅 您的服务

export class SomeComponent {

  currentValue: string;

  constructor(private someService: SomeService) {
    someService.getSomeObservable().subscribe(result => {
      this.currentValue = result ;
    });
  }
Levi
2020-06-21

您的 quizMetadata 未正确受初始值影响。应改为:

quizMetadata: {
    totalQuestions: number;
    correctAnswersCount$: Observable<number>;
    percentage: number;
    completionTime: number;
  };

请按如下操作:

quizMetadata = {
    totalQuestions: number;
    correctAnswersCount$: Observable<number>;
    percentage: number;
    completionTime: number;
  };
Berchmans
2020-06-21

使所有属性可选并使用空对象初始化

quizMetadata: {
    totalQuestions: number;
    correctAnswersCount$: Observable<number>;
    percentage: number;
    completionTime: number;
};

quizMetadata: {
    totalQuestions ?: number;
    correctAnswersCount$ ?: Observable<number>;
    percentage ?: number;
    completionTime ?: number;
} = {};
Msk Satheesh
2020-06-22