首页 > 解决方案 > 使用 Observable 获取数据时,需要使用detector.detectChanges Angular v6+

问题描述

我的 Angular 项目中有一个奇怪的错误。当我使用模拟 API 从本地数据中获取数据时,一切正常,但是当我切换到在线 API 并使用Observablesubscribe 方法获取数据时,我的角度模板视图中的数据不会更新。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);
}

并在我的角度.ts文件中获取数据,如下所示:

this.myService.getData().subscribe(result => {
    this.myData = result;
    // this.detector.detectChanges();
})

myData// this.detector.detectChanges()除非我取消注释方法,否则不会在角度模板中更新变量。

并且detectChanges是从下面的角度库中导入的:

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>

标签: angularrxjsobservabletwo-way-binding

解决方案


与我不喜欢在 HTML 中执行异步的注释不同,我以与您在上面编码的方式相同的方式执行此操作。我的问题是您ChangeDetectionStrategy对组件的设置是什么。其中一些不会自动通知更改并更新 UI(这可以解释您的问题)。

这是因为,在app.component.ts模板中,它changeDetectionStrategy.onPush基本上是在角度上下文中发生任何事情时使用的,我应该使用类似detector.detectChanges(). 只需使用changeDetectionStrategy.Default一切都会正常,角度双向绑定可以正常工作。


推荐阅读