打字稿全局变量:计数器

时间:2018-04-04 00:08:57

标签: typescript angular5

模板不能也不使用* ngFor。当遇到incrementQuestionNumber()的每次出现时,我需要一个实现来递增并显示计数器。我的组件中注入了Globals类,但抛出了ExpressionChangedAfterItHasBeenCheckedError异常。

模板:

<div>
{{ globals.incrementQuestionNumber() }}. What is your favorite color?
</div>
<div>
{{ globals.incrementQuestionNumber() }}. What is your favorite car?
</div>
<div>
{{ globals.incrementQuestionNumber() }}. Who is your favorite person?
</div>

打字稿:

import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
    static question_number: number = 1;

    incrementQuestionNumber() {
        return ++Globals.question_number;
    }
}

更新 如果最终实施不明显(对其他人),下面提供了另一个问题:

import {Directive, ElementRef} from '@angular/core';
import { Globals } from './globals';

@Directive({
  selector: '[counter]'
})
export class CounterDirective {

  constructor(private globals: Globals, private  el: ElementRef) {
  let counter = globals.incrementQuestionNumber();
  let html = el.nativeElement.innerHTML;
  let match = html.match(/^(\d+)/)
  if (match === null)
      el.nativeElement.innerHTML = counter + '. ' + html; // Doesn't execution when tab is navigated to...
  }

}

1 个答案:

答案 0 :(得分:1)

Globals滥用静态属性。由于服务预计是单例(当它在模块中提供时它是单例),它应该是:

@Injectable()
export class Globals {
    question_number: number = 1;

    incrementQuestionNumber() {
        return ++this.question_number;
    }
}

{{ globals.incrementQuestionNumber() }}自然会导致ExpressionChangedAfterItHasBeenCheckedError,因为它不仅会在每次出现时增加,而且在每次表达式评估时都会增加,但它不稳定。

要在模板中每次出现增加一次,它应该是指令或组件:

@Directive({ selector: '[question]' })
class QuestionDirective {
  constructor(public globals: Globals) {
    globals.incrementQuestionNumber();
  }

  ngOnDestroy() {
    // decrement question number?
  }
}

使用方法如下:

<div question>What is your favorite color?</div>

由于'问题'实体可能应该提供的不仅仅是一个字符串,QuestionDirective可能负责其他与问题相关的事情并成为一个组件。

相关问题