将数据从一个组件传递到另一个组件的角度

问题描述 投票:1回答:1

我正在使用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;
      });
    }

请您帮忙。谢谢!

angular rxjs
1个回答
0
投票

我认为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);
  });         
}
© www.soinside.com 2019 - 2024. All rights reserved.