我試圖在使用Observables旁邊的ChangeDetectionStrategy.OnPush
時,圍繞最佳實踐環繞我的頭。Angular 2中的ChangeDetectionStrategy.OnPush和Observable.subscribe
的例子演示了想要表現出一定的加載消息(或者簡單的微調動畫也許)的常見場景:
@Component({
selector: 'my-app',
template: `Are we loading?: {{loadingMessage}}`,
// Obviously "Default" will notice the change in `loadingMessage`...
// changeDetection: ChangeDetectionStrategy.Default
// But what is best practice when using OnPush?
changeDetection: ChangeDetectionStrategy.OnPush
})
export class App implements OnInit {
private loadingMessage = "Wait for it...";
constructor() {
}
ngOnInit() {
// Pretend we're loading data from a service.
// This component is only interested in the call's success
Observable.of(true)
.delay(2000)
.subscribe(success => {
if(success){
console.log('Pretend loading: success!');
// OnPush won't detect this change
this.loadingMessage = 'Success!';
}
});
}
}
我或多或少理解具有不變性的要求OnPush
,對我而言,至少在討論實際模型數據(可能在某種商店中持有)時它是有意義的。
所以,我有兩個問題:
- 爲什麼沒有新的字符串值的分配
'Success!'
觸發這種改變探測器?就不變性而言,價值已經改變了,對嗎? - 使用
ChangeDetectionStrategy.OnPush
時應該如何實現輕量級內部組件狀態(即loadingMessage
)?如果有多種最佳實踐,請指出正確的方向。
感謝您的全面解答。我在想,最好的解決方案是'markForCheck()'(我對這是否有點冒險或可以接受是有界限的)。或者創建一個'loadingMessage'或'state'作爲一個'Observable'本身,這樣它可以代表多個狀態,按照[plnkr](http://plnkr.co/edit/OiBSDA8Kcsgl4vBF15xW?p=preview)。我想我會將其添加到您的答案中並接受,因爲它似乎涵蓋了所有基數。 –
@PhilipBulley,'markForCheck()'不是很好。 [ChangeDetectorRef API文檔](https://angular.io/docs/ts/latest/api/core/ChangeDetectorRef-class.html)顯示了一個與您的用例非常相似的示例:具有「OnPush」的組件具有「在setTimeout()'回調中更新的numberOfTicks屬性,調用'markForCheck()'以確保視圖更新。 –
感謝您使用示例進行說明。 –