我的加载指示器出错,我不明白为什么:
LoadingIndicatorComponent.html:2 ERROR错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后发生了变化。上一个值:'hidden:true'。当前值:'hidden:false'。
我有一个简单的加载指示图像:
<img class="loader" [hidden]="!isLoading" src="loading.svg" alt="Loading..." />
使用以下代码:
export class LoadingIndicatorComponent implements OnInit {
public isLoading = false;
constructor(private loader: LoadingIndicatorService) {
}
ngOnInit() {
this.loader.IsLoading.subscribe((value) => {
this.isLoading = value;
});
}
}
使用以下服务:
export class LoadingIndicatorService {
constructor() { }
private workload = 0;
private _loading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public readonly IsLoading: Observable<boolean> = this._loading.asObservable();
public StartWork(): void {
this.workload++;
this._loading.next(this.workload > 0);
}
public EndWork(): void {
this.workload--;
this._loading.next(this.workload > 0);
}
}
答案 0 :(得分:1)
您正在修改导致问题的更改检测周期中isLoading
的值。这是一行代码
this.loader.IsLoading.subscribe((value) => {
this.isLoading = value;
});
正由您的服务修改加载。所以你需要解决这个问题
this.loader.IsLoading.subscribe((value) => {
Promise.resolve(null).then(() => this.isLoading = value);
});
回答基于这篇文章:Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError
error
答案 1 :(得分:0)
我也遇到过这种类型的问题。使用此
this.loader.IsLoading.subscribe((value) => {
setTimeout(() => this.isLoading = value, 0)
});