【问题标题】:How do I get a string value from service in an Angular component?如何从 Angular 组件的服务中获取字符串值?
【发布时间】:2020-08-24 08:34:52
【问题描述】:

我正在尝试从我的 QuizService 中获取字符串变量 explainText 的值,以使用数据绑定在我的 di-quiz 组件模板中显示。选择答案时,console.log 显示未定义的说明文本,并且模板的数据绑定未显示任何说明文本。请看:https://stackblitz.com/edit/angular-9-quiz-app

知道为什么这不起作用吗?请你帮忙。谢谢!

在我的 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; };
@Input() set explanation(value: string) { this.explanationText = value; };

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

在我的 di-quiz.component.html 中,我有

<section id="question" [class.answered]="answer">
  <span *ngIf="!answer">{{ question?.questionText }}</span>
  <span *ngIf="answer">{{ explanationText }}</span>
</section>

【问题讨论】:

  • 首先尝试在你的服务中初始化说明文本
  • 在上面的代码中explanationText 是未初始化的。你是如何在QuizService 中初始化它的?
  • 我在 setExplanationAndCorrectAnswerMessages() 函数中设置说明文本(见上文)。
  • 我已经尝试了以下代码,但仍然无法让它工作:@Input() set explainTextVal(value) { this.explanationText = value; }; ngOnChanges(changes: SimpleChanges) { if (changes.explanationTextVal && changes.explanationTextVal.currentValue !== changes.explanationTextVal.firstChange) { this.explanationText = changes.explanationTextVal.currentValue; } }
  • @multiv123 你发布了一个非常难以理解的巨大堆栈闪电战。设计有很多错误,因此这里的简单答案并不能解决您的问题——您需要重新设计整个项目。你的项目是基于这个github.com/marvinrusinek/codelab-quiz吗?

标签: angular typescript dependency-injection angular-services angular2-databinding


【解决方案1】:

我检查了您的 stackblitz 代码并发现了问题。这是因为您在 DependencyInjectionQuizComponent 和 QuestionComponent 中注册了 QuizService,这会创建多个实例。

因此,当问题组件触发 setExplanationAndCorrectAnswerMessages 时,它会在不同实例中更新说明文本,但您的 DIQuizComponent 期望来自不同实例。

要解决此问题,您必须从 QuestionComponent 提供程序中删除 QuizService。

我已经分叉并更新了代码。这是link

【讨论】:

  • 谢谢!没想到这么简单。我在看代码。我需要对correctAnswerMessage 进行类似的更改。
  • 好像只有回答正确才显示说明文字,否则问题框为空。
  • 您需要检查逻辑或条件如何显示它。我没有检查。
【解决方案2】:

像这样改变上面的构造函数,

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);
}

【讨论】:

  • 我需要由我的服务中的 setExplanation 函数确定的解释文本的值。
猜你喜欢
  • 2018-11-18
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多