假设我有一个大的Json模型,我的后端发送给我的前端,它看起来像这样:
{
dataA: { //some object },
dataB: { //some object },
dataC: { //some object },
...
}
现在假设我有以dataA为@Input()
的ComponentA,以dataB为@Input()
的ComponentB,等等:
@Component({
selector: 'comp-a'
})
class ComponentA {
@Input() _dataA;
}
@Component({
selector: 'comp-b'
})
class ComponentA {
@Input() _dataB;
}
// .... other components
@Component({
selector: 'app',
template:`
<comp-a [_dataA]="dataA"></comp-a>
<comp-b [_dataB]="dataB"></comp-b>
...
`
})
class AppComponent {
}
我想让这些组件使用OnPush变更检测策略。
当接收到新模型时,可能会发生模型中的数据字段与前一个模型中的值没有变化的情况,因此我不希望它们再次作为@Input()
传递给组件,以避免运行无用的更改检测。
在将数据作为@Input()
传递给组件之前,有没有一种聪明的方法可以在前端检测模型中的更改,并仅在它们各自的数据更改时通知它们?或者我应该让Angular自己执行变化检测?OnPush真的适合这里吗?
发布于 2019-03-12 07:35:38
OnPush通过不检查模型属性来提高效率,并在对象的实例更改时触发更新,而不是更改对象的属性。要执行您提议的操作,需要检查对象的属性,以查看是否有任何更改。你基本上是在重新发明变化检测,所以我看不出有什么意义,你需要做得比Angular团队做得更好才能看到任何好处。
您还使用rxjs标记了此问题,但问题中没有任何关于rxjs的内容。实现OnPush更改检测的最好方法是使用rxjs可观察性,并在模板中使用异步管道。这样,您只需要让可观察对象发出更新值。
@Component({
selector: 'app',
template:`
<comp-a [_dataA]="dataA$ | async"></comp-a>
<comp-b [_dataB]="dataB$ | async"></comp-b>
...
`
})
class AppComponent {
dataA$ = new BehaviorSubject<DataAModel>(undefined);
dataB$ = new BehaviorSubject<DataBModel>(undefined);
updateA() {
if (a has changed) { // If your detection to check changes is inefficient then there is no point
this.dataA$.next(a);
}
}
updateB() {
if (b has changed) {
this.dataB$.next(b);
}
}
}
https://stackoverflow.com/questions/55111660
复制相似问题