Angular 模板在更改时不更新我的变量

Angular template doesn't update my variable when it changes

我有一个名为 history 的数组,它从我的 chrome 扩展中的后台脚本更新,我想 实时显示 有多少当我 运行 脚本并在我的弹出窗口中显示它时,它正在获取“类型 1”,这就是我在我的 .ts 文件中处理它的方式

  history: Report[] = [];
  classOne = 0;
  
  classOneSubject = new BehaviorSubject(this.classOne);
  classOneObs = null;

  constructor() { }

  ngOnInit(): void {
    chrome.storage.onChanged.addListener((changes, area) => {
      if (area === 'sync' && 'history' in changes) {
        this.history = changes.history.newValue;
        this.classOneSubject.next(this.history.filter(e => e.ctype === 1).length);
        this.classOneObs = this.getClassOneTypes();
      }
    });
  }

  getClassOneTypes(): any {
    return this.classOneSubject.asObservable();
  }

这是我的弹出窗口

<em class="stat mt-3 mb-1">{{classOneObs | async}}</em>

但是它并没有实时更新值,出于某种原因,它只会在我按下 button/link 时显示新值,即使这些值没有执行任何操作,这很奇怪,我不明白为什么会发生。我做错了什么?

尝试手动 运行 更改检测。

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
  ) { }

  ngOnInit(): void {
    chrome.storage.onChanged.addListener((changes, area) => {
      if (area === 'sync' && 'history' in changes) {
        this.history = changes.history.newValue;
        this.classOneSubject.next(this.history.filter(e => e.ctype === 1).length);
        this.classOneObs = this.getClassOneTypes();
        this.changeDetectorRef.detectChanges();  // Add this line.
      }
    });
  }