我正在使用Angular开发测验应用程序,我需要在ResultsComponent中获取correctAnswersCount的值。当我真的需要总正确答案计数的值时,我为correctAnswersCount得到的值为0。我认为代码是正确的,只是我得到的值是错误的。到目前为止,这是我的代码:
在quiz.service.ts中:
export class QuizService {
correctAnswersCountSubject = new BehaviorSubject<number>(0);
correctAnswersCount: number;
sendCountToResults(value) {
this.correctAnswersCount = value;
this.correctAnswersCountSubject.next(this.correctAnswersCount);
}
}
在我的DI-Quiz组件中:
ngOnInit() {
this.quizService.correctAnswersCountSubject.subscribe(data => {
this.count = data + 1;
});
this.passCountToQuizService(this.count);
}
passCountToQuizService(count) {
this.quizService.sendCountToResults(count);
}
和在ResultsComponent中:
constructor(private quizService: QuizService) {
this.quizService.correctAnswersCountSubject.subscribe(data => {
this.correctAnswersCount = data;
});
}
请您帮忙。谢谢!
我认为this.passCountToQuizService(this.count);
应该在函数委托中,因为如果没有,您将在组件初始化时仅以零传递它,而不是在每次调用订阅时传递它:
而不是:
ngOnInit() {
this.quizService.correctAnswer$.subscribe(data => {
this.count = data + 1;
});
this.passCountToQuizService(this.count);
}
执行:
ngOnInit() {
this.quizService.correctAnswer$.subscribe(data => {
this.count = data + 1;
this.passCountToQuizService(this.count);
});
}