【发布时间】:2020-01-21 00:03:23
【问题描述】:
我的 Angular 项目中有一个奇怪的错误。当我使用模拟 API 从本地数据中获取数据时,一切正常,但是当我切换到在线 API 并使用 Observable 订阅方法获取数据时,我的角度模板视图中的数据不会更新。只有当我调用detector.detectChanges() 方法时才会更新。
简而言之,在使用在线 API 时,双向数据绑定仅在我调用 detectChanges 时才有效。
例如想象下面的场景:
data = [some data here...]
getData(): Observable<any> {
return of(this.data);
}
当我在.ts 文件中调用此方法并使用它获取数据时,角度模板将自动更新。但是当我切换到下面的代码时:
getData(): Observable<any> {
let url = `${this.API_URL}/fetchData/`;
return this.http.get(url);
}
并在我的 Angular .ts 文件中获取数据,如下所示:
this.myService.getData().subscribe(result => {
this.myData = result;
// this.detector.detectChanges();
})
myData 变量不会在角度模板中更新,除非我取消注释 // this.detector.detectChanges() 方法。
而detectChanges是从下面的angular库中导入的:
private detector: ChangeDetectorRef,
谁能帮我克服这个错误?这真的很烦人,我的代码现在到处都有很多detectChanges,就在任何需要双向数据绑定的代码之后!
提前致谢
更新
我的 .html 文件
<table class="table table-bordered table-striped table-responsive"
style="display: inline-table;">
<thead>
<tr style="left: 0;">
<th><span>test</span></th>
</tr>
</thead>
<tbody>
<tr style="left: 0;" *ngFor="let d of myData">
<td>{{d.test}}</td>
</tr>
</tbody>
</table>
【问题讨论】:
-
为什么不直接将
this.myService.getData()设置为this.myData,使其成为Observable,并在模板中使用async管道(例如myData | async)? -
你能解释更多细节,也许在答案部分。我真的很感激任何帮助;)
-
你能先给我们看看你的模板(.html)吗?
-
这是正常的 html。我更新了它的一部分。
-
检查
changeDetection: ChangeDetectionStrategy.OnPush在你的@Component装饰器配置中。删除它,如果您希望 angular CD 在发生异步事件后为您进行脏检查。
标签: angular rxjs observable two-way-binding