我正在构建一个经典的应用程序,它从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在加载程序消失之前很久就显示了这个值。
因此,我的结论是,在某种程度上,模板的呈现是延迟完成的,但是只有当应用程序在浏览器中第一次初始化时才能完成。
发布于 2019-11-07 08:30:12
我设法通过强制进行更改检测来修复它。
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)
})
);
}https://stackoverflow.com/questions/58744433
复制相似问题