【问题标题】:Angular data appears on console.log but not in the component view角度数据出现在 console.log 上,但不在组件视图中
【发布时间】:2020-10-09 19:09:02
【问题描述】:

我正在使用 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;
      }
    );
  }

}

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

【问题讨论】:

  • 您在使用 ChangeDetectionStrategy.OnPush 吗?如果是,请把它注释掉,那么它应该可以工作。
  • 控制台有错误吗?
  • 你能提供一个链接吗?
  • 不,我没有使用 ChangeDetectionStrategy.OnPush 并且完全没有错误。
  • @joe2020wow 检查这个:stackblitz.com/edit/angular-demo-service-gbhx2i 在这里工作正常

标签: angular typescript rxjs angular9


【解决方案1】:

不确定为什么第一次没有触发更改检测。尝试使用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
      }
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多