簡體   English   中英

Angular - ExpressionChangedAfterItHasBeenCheckedError:檢查后表達式已更改

[英]Angular - ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

我真的無法理解這一點,我已經嘗試在谷歌中搜索,在這里,無處不在......我不明白為什么這個錯誤仍然顯示。

我有這樣的事情:

父.html

<child-1 [(type)]="type"></child-1>

父母.ts

type = 0;
getTypeToOtherthings() { // function to use in a mouse event, it's not important for that
    console.log(type);
}

child-1.html

<child-2 [(type)]="type">

child-1.ts // 這個組件就像是 parent 和 child-2 之間的橋梁(可能問題出在這里,我真的不知道)

_type: number;
@Input() set type(val: number) {
  this.typeChange.emit(val);
  this._type= val;
}
get type() {
  return this._type;
}
@Output() typeChange: EventEmitter<number> = new EventEmitter<number>();

child-2.html

(一些 HTML)

child-2.ts

_type: number;
@Input() set type(val: number) {
  this.typeChange.emit(val);
  this._type= val;
}
get type() {
  return this._type;
}
@Output() typeChange: EventEmitter<number> = new EventEmitter<number>();

/*I need change Type variable in childs-2, so i put this in 
onInit (but i already tryed put this in all Afters... , using Promise, ChangeDetectorRef, nothing works,
like everything works fine but the error still)*/
ngOnInit() {
    this.type = 2;
}

畢竟我幾乎要放棄了

又快又臟,但是如果你看到這個問題並且知道問題所在,你可以在 setTimout 中運行它,例如

setTimeout(()=> this.markersEventsType = 2;)

但可能有更合適的解決方案。 在構造函數中設置 eventType 不起作用嗎? 如果您從服務中獲得更改,您是否嘗試過使用異步管道?

這表明您的應用存在問題。 簡而言之,您正在修改模型而不是視圖。 Angular 的 devMode 除了已經存在的更新檢查之外,還添加了更新檢查。 這些檢查會查找模型中的任何更新,以便更新視圖。

您收到此錯誤是因為這些檢查均未設法檢測到模型中的更改。 因此,一種解決方案是使用ChangeDetectorRef 調用detectChanges()告訴您的應用模型中的某些內容發生了變化並且可以更新 vue。

除了這個答案,我強烈建議您查看更改檢測策略,在我看來,它使代碼更易於理解(因為它迫使您使用 ChangeDetection),並且以更一般的方式,您的應用程序將運行得更流暢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM