【问题标题】:How can I prevent Firebase from repeatedly triggering change detection in Angular 2?如何防止 Firebase 在 Angular 2 中重复触发变更检测?
【发布时间】:2017-01-04 03:59:22
【问题描述】:

由于 Angular/Zone 猴子补丁 websocket 和 setInterval 等原因,Firebase 使用了大量内部异步调用来触发更改检测。即使我没有与我的应用程序交互,我也会看到一连串的更改检测发生时间,这有助于减慢速度,尤其是在移动设备上。

这种默认行为可能很有用,但我现在使用 Firebase 的方式我可以非常严格地控制何时需要更新视图,因此 Firebase 的回调以这样一种方式使用,即更改检测将手动发生无论如何。

我知道将更改检测器策略设置为 OnPush 会有所帮助,我正在努力,但我想从各个角度进行攻击。

我熟悉区域的 runOutsideAngular,但现在不确定是否在此处应用它,因为所有异步调用都发生在 Firebase 模块内。

如何让 Firebase 在 Angular 区域之外开展所有业务?


编辑:显示问题的示例代码:

import {Component} from '@angular/core';

@Component({
  selector: 'test-component',
  template: 'hello world'
})
export class TestComponent {
  ref: Firebase;

  constructor() {
    this.ref = new Firebase('<firebase URL>');
  }

  ngDoCheck() {
    console.log('Check the stack - this is being called continually via async functions used internally by Firebase.');
    debugger;
  }
}

【问题讨论】:

    标签: angular firebase firebase-realtime-database angular2-changedetection zonejs


    【解决方案1】:

    回想起来,这很明显,但只需在区域之外实例化 Firebase 引用就可以了。例如:

    import {Injectable, NgZone} from '@angular/core';
    
    // ...
    
    @Injectable()
    export class DataService {
      ref: Firebase;
    
      // ...
    
      constructor(
        private zone: NgZone
        // ...
      ) {
        // Instantiate Firebase ref outside the zone to prevent its continual internal operations from triggering change detection
        this.zone.runOutsideAngular(() => {
          this.ref = new Firebase('<firebase URL>');
        });
    
        this.ref.on('value', snapshot => {
          // Change detection will NOT automatically be triggered after this callback
        });
      }
    }
    

    通过在我的组件中的ngDoCheck 中设置断点,我能够将所有更改检测周期追溯到我实例化 Firebase 引用的那一行,这暗示在区域外运行它会阻止它们。

    请注意,如果您选择这条路线,您必须确保在必要时触发更改检测。有关示例,请参阅https://stackoverflow.com/a/34829089/458614

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      • 2016-04-22
      • 2016-06-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多