在执行一些包含大量计算的同步操作时,显示之前和之后的内容可能是一个问题。
组件模板:
<div>
<my-spinner *ngIf="myService.isLoading"></my-spinner>
</div>
服务
@Injectable()
export class MyService {
private isLoading = false;
constructor() {}
myFunction() {
this.isLoading = true;
this.calculateSomethingSuperHeavyThatTakes5seconds();
this.isLoading = false;
}
}
执行 myFunction 实际上不会显示微调器。
我修复的一种方法是用 setTimeout 包装繁重的函数,如下所示:
myFunction() {
this.isLoading = true;
setTimeout(() => {
this.calculateSomethingSuperHeavyThatTakes5seconds();
this.isLoading = false;
});
}
它有效,但对我来说不是一个干净的解决方案。myFunction() 中的 applicationRef.tick(),将 myFunction 内容包装在 this.zone.run() 或 changeDeetctionRef.detectChanges() 变体中并不能解决问题。