![](/img/trans.png)
[英]ExpressionChangedAfterItHasBeenCheckedError . Angular 2(5) *ngIf
[英]ExpressionChangedAfterItHasBeenCheckedError in ngIf?
我不知道我在這里錯過了什么。
共享服務A:
export class SharedServiceA {
somethingWasUpdated = new Subject();
updateSomething(value) {
this.somethingWasUpdated.next(value);
}
}
另一個服務:
export class AnotherService {
doSomething() {
this.sharedServiceA.updateSomething(true);
}
}
組件-a.component.ts
export class ComponentA {
list = [];
isShowList = false;
ngOnInit() {
this.sharedServiceA.somethingWasUpdated
.pipe(takeUntil(this.destroyed))
.subscribe(
data => {
if (data) {
this.fetchData(); // Get data from another service, then populate list
}
}
);
}
fetchData() {
// Get data from another service
if (dataFound) {
this.list = dataFound;
this.isShowList = true;
} else {
this.isShowList = false;
}
}
}
組件-a.component.html
<div *ngIf="!isShowList"> <!-- This is where ExpressionChangedAfterItHasBeenCheckedError points to: Previous value: 'ngIf: true'. Current value: 'ngIf: false' -->
List empty
</div>
<div *ngIf="isShowList">
Print something here
</div>
組件-b.component.html
export class ComponentB {
ngOnInit() {
this.sharedServiceA.somethingWasUpdated
.pipe(takeUntil(this.destroyed))
.subscribe(
data => {
if (data) {
// Get data from another service
}
}
);
this.anotherService.doSomething(); // If I place this inside a setTimeout, I don't get the ExpressionChangedAfterItHasBeenCheckedError
}
}
這是場景:
單擊按鈕 > ComponentA
在選項卡內創建
單擊另一個按鈕 > ComponentB
在另一個選項卡中創建(基本上與ComponentA
並排)> ComponentA.fetchData()
> ExpressionChangedAfterItHasBeenCheckedError
為什么在填充list
並將isShowList
設置為true
后我會在ComponentA
中得到ExpressionChangedAfterItHasBeenCheckedError
,為什么我放置this.anotherService.doSomething();
時不會收到錯誤? 在setTimeout
里面?
這段代碼如何違反單向數據流? 即使閱讀了幾篇文章,我仍然對這種特殊情況感到困惑。
快點,ExpressionChangedAfterItHasBeenChecked 錯誤僅在開發模式下可見。 不要在生產模式下顯示。
在您的組件中使用如下所示的 changeDectorRef:
import { ChangeDetectorRef} from "@angular/core";
constructor(private ref: ChangeDetectorRef){}
fetchData() {
// Get data from another service
if (dataFound) {
this.list = dataFound;
this.isShowList = true;
} else {
this.isShowList = false;
}
this.ref.detectChanges();
}
第二種方法
如果以上對您不起作用,請在AfterViewChecked
生命周期掛鈎中使用它。
ngAfterViewChecked() {
this.ref.detectChanges();
}
希望這對你有幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.