【问题标题】:Angular: Model listening with ChangeDetectionStrategy.OnPushAngular:使用 ChangeDetectionStrategy.OnPush 进行模型监听
【发布时间】:2019-03-12 07:51:17
【问题描述】:

假设我有一个大型 Json 模型,我的后端发送到我的前端,看起来像这样:

{
     dataA: { //some object },
     dataB: { //some object },
     dataC: { //some object },
     ...
}

现在假设我有 ComponentA 将 dataA 作为@Input(),ComponentB 将 dataB 作为@Input() 等等:

@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 在这里真的合适吗?

【问题讨论】:

    标签: angular rxjs angular2-changedetection


    【解决方案1】:

    OnPush 通过不检查模型属性来提高效率,并在对象实例发生更改时触发更新,而不是对象的属性。要执行您的建议,需要检查对象的属性以查看是否有任何更改。你基本上会重新发明变更检测,所以我看不出重点,你需要做得比 Angular 团队做得更好才能看到任何好处。

    您还用 rxjs 标记了这个问题,但问题中没有关于 rxjs 的内容。实现 OnPush 更改检测的最佳方法是使用 rxjs 可观察对象并在模板中使用异步管道。这样你就只能让 observable 发出更新的值。

    @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);
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多