首页 > 解决方案 > Angular 8 - 初始加载时值更改和模板渲染之间的延迟

问题描述

我正在构建一个经典应用程序,该应用程序从其主页上的 http 调用加载数据。获取数据时会显示加载程序。

初始化应用程序时,第一次 http 调用的加载时间异常长。之后,速度非常快,即使在刷新页面后也是如此。

我在网络检查器中注意到,调用实际上在加载程序消失之前很久就完成了。在这里和那里放了一些之后console.log,数据被提取并准备好使用,加载器设置为 false 但它仍在显示。

组件

this.villageService.getVillages().subscribe({
    next: (villages: Village[]) => {
        this.villages = villages.map(village => new Village().fromJson(village));
        this.isLoading = false;
        console.log(this.villages);
        console.log(this.isLoading);
    },
    error: (error: any) => {
        this.isLoading = false;
    },
    complete: () => (this.isLoading = false)
});

模板

<div class="row">
    <app-village-card
        *ngFor="let village of villages | orderByProperty: 'title'"
        class="col-12 col-sm-6 col-lg-6 col-xl-4"
        [village]="village"
    >
    </app-village-card>
</div>
<app-loader [isLoading]="isLoading" mode="spinner">Loading...</app-loader>

两者console.log在加载器消失之前很久就显示了该值。

所以,我的结论是,不知何故,模板的渲染是延迟完成的,但只有当应用程序第一次在浏览器中初始化时。

标签: htmlangular

解决方案


我设法通过强制更改检测来修复它。

constructor(
    private changeDetector: ChangeDetectorRef
) {}

getVillages() {
    this.isLoading = true;
    this.subscriptions.add(
        this.villageService.getVillages().subscribe({
            next: (villages: Village[]) => {
                this.villages = villages.map(village => new Village().fromJson(village));
                this.isLoading = false;
                this.changeDetector.detectChanges(); // -------> this line
            },
            error: (error: any) => {
                this.isLoading = false;
            },
            complete: () => (this.isLoading = false)
        })
    );
}

推荐阅读