[英]change detection of property in Angular
在app.component.ts中,我有一個稱為current的屬性。
export class appComponent {
current = 0;
}
在某些方法中,我更改了此屬性
previous() {
this.current -= 1
}
next() {
this.current += 1
}
現在,我想在更改當前屬性時運行一組命令。 我可以通過在更改后附加這些命令來做到這一點。
previous() {
this.current -= 1;
this.runCommands();
}
next() {
this.current += 1;
this.runCommands();
}
一切正常。 但是請注意,每次此屬性更改時調用此方法似乎都很混亂。 我想執行的更改檢測功能就像運行我的命令一樣:
this.current.valueChanges.subscribe(() => this.runCommand());
用更簡單的方法可以實現角度嗎?
提前致謝
您可能希望通過BehaviorSubject
使current
成為Observable
。 理想情況下,這些將存在於可注入服務中,然后依賴於current
值的組件將通過注入服務進行預訂。
設置Observable
看起來像
private _current = new BehaviorSubject<number>(0);
public readonly current = this._current.asObservable();
然后我們可以訂閱需要喜歡的組件(在此示例中為組件所在的組件)中的current
this.current.subscribe(val => {
// do stuff here
})
每當我們希望更改current
的值並為訂閱的任何事件觸發事件時,我們都會這樣做
this._current.next(123); // anything subscribed receives the value of 123
您可以在組件中執行此操作,但是最佳實踐是將Observable
放在服務層中。
為了實現將值增加1或-1的理想用例, BehaviorSubject
函數getValue()
將通過告訴您存儲在Observable
的當前值來派上用場。
this._current.next(++this._current.getValue()) // increment 1
this._current.next(--this._current.getValue()) // increment -1
// etc...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.