html - 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
在加载器消失之前很久就显示了该值。
所以,我的结论是,不知何故,模板的渲染是延迟完成的,但只有当应用程序第一次在浏览器中初始化时。
解决方案
我设法通过强制更改检测来修复它。
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)
})
);
}
推荐阅读
- vuejs2 - 如何避免vue组件重绘?
- postgresql - 索引中的碎片是如何发生的?
- vsto - 保存到约会项目后,Outlook VSTO AddIn 中的 ItemChange 被多次调用
- javascript - 编写 JavaScript 条件语句对三个数字进行排序
- java - Windows 更新后 Android Studio AVD 模拟器透明
- javascript - 在 chrome 本地存储中附加一个数组
- php - MySQL UPDATE WHERE 的行为与 SELECT WHERE 不同
- python - Kafka Python 使用自定义时间戳发送数据
- r - 使用 mvrnorm 预测相关值并包括时间自相关
- php - prestashop中用户帐户注册的php href