角度从组件中的服务获取字符串值

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

我正在尝试从QuizService中获取字符串变量的值,以显示在di-quiz组件的模板中,以使用数据绑定进行显示。

在我的quiz.service.ts文件中,我有:

@Injectable({providedIn: 'root'}) {
  export class QuizService {
  explanationText: string;
  ...

  setExplanationAndCorrectAnswerMessages() {
    this.question = this.getQuestion;
    if (this.question) {
      if (this.correctAnswers.length === 1) {
        this.explanation = ' is correct because ' + this.question.explanation + '.';
      }
      if (this.correctAnswers.length > 1) {
        this.explanation = ' are correct because ' + this.question.explanation + '.';
      }
    }

    if (this.correctAnswers && this.correctAnswers.length === 1) {
      const correctAnswersText = this.correctAnswers[0];
      this.explanationText = 'Option ' + correctAnswersText + this.explanation;
      console.log(this.explanationText);
      this.correctAnswerMessage = 'The correct answer is Option ' + this.correctAnswers[0] + '.';
      console.log(this.correctAnswerMessage);
    }
    if (this.correctAnswers && this.correctAnswers.length > 1) {
      if (this.correctAnswers[0] && this.correctAnswers[1]) {
        const correctAnswersText = this.correctAnswers[0] + ' and ' + this.correctAnswers[1];
        this.explanationText = 'Options ' + correctAnswersText + this.explanation;
        console.log(this.explanationText);
        this.correctAnswerMessage = 'The correct answers are Options ' + correctAnswersText + '.';
        console.log(this.correctAnswerMessage);
      }
      ...
    }
  }

在我的[[di-quiz.component.ts中,我有一个getter / setter和构造函数,如下所示:

get explanation(): string { return this.quizService.explanationText; }; set explanation(value: string) { this.quizService.explanationText = value; }; constructor(private quizService: QuizService, private timerService: TimerService, private route: ActivatedRoute) { this.explanationText = this.explanation; console.log("ExpTxt: " + this.quizService.explanationText); }
并且在我的

di-quiz.component.html

中,我有<section id="question" [class.answered]="answer"> <span *ngIf="!answer">{{ question?.questionText }}</span> <span *ngIf="answer">{{ explanationText }}</span> </section>
console.log显示的是undefinedText的未定义,并且选择答案后,与模板的数据绑定不显示任何的explorationText的内容。关于为什么这不起作用的任何想法吗?
angular angular-services
1个回答
0
投票
更改上面的构造函数,

constructor( private quizService: QuizService, private timerService: TimerService, private route: ActivatedRoute ) { this.explanation = 'Text you want'; this.explanationText = this.explanation; console.log("ExpTxt: " + this.quizService.explanationText); }

© www.soinside.com 2019 - 2024. All rights reserved.