Angular 数据出现在 console.log 但不在组件视图中

Angular data appears on console.log but not in the component view

我正在使用 Angular 9,我有这个代码:

app.component.html

<br><br>
<div class="container-fluid">
  <div class="row">
    <div class="col-md-12">

      <input #cmd />
      <button (click)="runCommand2(cmd.value)">runCommand</button>
      <br><br>


      RESULT: {{ output }}


    </div>
  </div>
</div>

然后在我的app.component.ts

export class AppComponent {

  output: any;

  constructor(private myService: myService) {}

  runCommand2(command) {
    this.myService.executeShell2(command).subscribe(
      response => {
        if (response) { 
          this.output = response;
          console.log(this.output); // This appears in the console but does not appear in {{ output }} although the data is there
        }
      },
      error => {
        this.output = error;
      }
    );
  }

}

我还想提一下,由于某种原因,如果我再次调用该方法,输出将在第二次而不是第一次填充到视图上,尽管数据在那里。 关于问题可能是什么的任何想法?

不确定为什么第一次没有触发更改检测。尝试使用 detectChanges() 方法手动触发它。

import { Component, ChangeDetectorRef } from '@angular/core';

export class AppComponent {
  output: any;

  constructor(private myService: myService, private changeDetectorRef: ChangeDetectorRef) { }

  runCommand2(command) {
    this.myService.executeShell2(command).pipe(take(1)).subscribe(     // <-- use `take(1)` to complete after one notification
      response => {
        if (response) { 
          this.output = response;
          console.log(this.output); // This appears in the console but does not appear in {{ output }} although the data is there
        }
      },
      error => {
        this.output = error;
      },
      () => {
        this.changeDetectorRef.detectChanges();    // <-- trigger change detection here
      }
    );
  }
}