在与ChangeDetectionStrategy.OnPush
个观察值一起使用时,我正试图理解最佳实践.
该示例演示了希望显示某种加载消息(或简单的微调器动画)的常见场景:
@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
的不变性要求,至少对我来说,目前在谈论实际的模型数据(可能保存在某种store 中)时这是有意义的.
所以,我有两个问题:
- 为什么新字符串值
'Success!'
的赋值不会触发更改检测器?就不变性而言,这个值已经改变了,对吗? - 当使用
ChangeDetectionStrategy.OnPush
时,应该如何实现轻量级内部组件状态(即loadingMessage
)?如果有多种最佳实践,请为我指出正确的方向.