角度数据显示在控制台上.log但不显示在组件视图中



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

然后在我的应用程序中。

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

最新更新