首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角8-初始加载时值变化与模板绘制之间的延迟

角8-初始加载时值变化与模板绘制之间的延迟
EN

Stack Overflow用户
提问于 2019-11-07 08:11:58
回答 1查看 636关注 0票数 0

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

当应用程序初始化时,我经历了第一个http调用的异常长的加载时间。在那之后,它非常快,即使在刷新页面之后。

我在网络检查器中注意到,调用实际上是在加载程序消失之前很长一段时间内完成的。在到处放置一些console.log之后,数据将被获取并准备使用,加载程序被设置为false,但它仍在显示。

组件

代码语言:javascript
复制
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)
});

模板

代码语言:javascript
复制
<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在加载程序消失之前很久就显示了这个值。

因此,我的结论是,在某种程度上,模板的呈现是延迟完成的,但是只有当应用程序在浏览器中第一次初始化时才能完成。

EN

回答 1

Stack Overflow用户

发布于 2019-11-07 08:30:12

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

代码语言:javascript
复制
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)
        })
    );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58744433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档