【发布时间】:2016-05-25 00:46:40
【问题描述】:
我正在尝试将 Observables 与 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 对不变性的要求,至少对我而言,目前在谈论实际模型数据(可能保存在某种商店中)时它是有意义的。
所以,我有两个问题:
- 为什么分配新字符串值
'Success!'不会触发更改检测器?就不变性而言,价值已经改变了,对吧? - 在使用
ChangeDetectionStrategy.OnPush时应该如何实现轻量级内部组件状态(即loadingMessage)?如果有多种最佳做法,请指出正确的方向。
【问题讨论】:
标签: javascript angular