请向我解释为什么我一直得到这个错误:ExpressionChangedAfterItHasBeenCheckedError:表达式已经改变后,它被检查。
显然,我只有在开发模式下才会遇到这种情况,在我的产品构建中不会出现这种情况,但这非常烦人,而且我根本不明白在我的开发环境中出现错误而不会在prod上显示的好处——可能是因为我缺乏理解。
通常,修复很简单,我只是把导致错误的代码包装在setTimeout中,就像这样:
setTimeout(()=> {
this.isLoading = true;
}, 0);
或者使用如下构造函数强制检测更改:
this.isLoading = true;
this.cd.detectChanges();
但是为什么我总是遇到这个错误呢?我想要了解它,这样我就可以在将来避免这些俗套的修复。
尝试了上面建议的大部分解决方案。只有在这种情况下对我有用。我使用*ngIf来切换角材料的不确定渐进条基于api调用,它抛出ExpressionChangedAfterItHasBeenCheckedError。
在上述组件中:
constructor(
private ngZone: NgZone,
private changeDetectorRef: ChangeDetectorRef,
) {}
ngOnInit() {
this.ngZone.runOutsideAngular(() => {
this.appService.appLoader$.subscribe(value => {
this.loading = value;
this.changeDetectorRef.detectChanges();
});
});
}
诀窍是使用ngzone绕过角分量的变化检测。
PS:不确定这是否是一个优雅的解决方案,但是使用AfterContentChecked和AfterViewChecked生命周期钩子必然会引起性能问题,因为你的应用程序会越来越大,因为它会被多次触发。
请遵循以下步骤:
1.
通过从@angular/core导入'ChangeDetectorRef'来使用它,如下所示:
import{ ChangeDetectorRef } from '@angular/core';
2.
在constructor()中实现,如下所示:
constructor( private cdRef : ChangeDetectorRef ) {}
3.
添加下面的方法到你的函数,你正在调用的事件,如点击按钮。它看起来是这样的:
functionName() {
yourCode;
//add this line to get rid of the error
this.cdRef.detectChanges();
}
当值在同一个更改检测周期中更改多次时,将发生此错误。我在一个TypeScript getter中遇到了这个问题,它的返回值经常变化。要解决这个问题,您可以限制一个值,使其在每个更改检测周期中只能更改一次,如下所示:
import { v4 as uuid } from 'uuid'
private changeDetectionUuid: string
private prevChangeDetectionUuid: string
private value: Date
get frequentlyChangingValue(): any {
if (this.changeDetectionUuid !== this.prevChangeDetectionUuid) {
this.prevChangeDetectionUuid = this.changeDetectionUuid
this.value = new Date()
}
return this.value
}
ngAfterContentChecked() {
this.changeDetectionUuid = uuid()
}
HTML:
<div>{{ frequentlyChangingValue }}</div>
这里的基本方法是每个变更检测周期都有自己的uuid。当uuid改变时,您就知道您已经进入了下一个循环。如果循环已经改变,则更新值并返回它,否则只需返回与之前在此循环中返回的值相同的值。
这确保每个循环只返回一个值。这对于频繁更新值很有效,因为更改检测周期发生得非常频繁。
为了生成uuid,我使用了uuid npm模块,但你可以使用任何方法来生成唯一的随机uuid。