首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何防止Firebase重复触发角度2中的变化检测?

如何防止Firebase重复触发角度2中的变化检测?
EN

Stack Overflow用户
提问于 2017-01-04 03:59:22
回答 1查看 638关注 0票数 3

Firebase使用了许多内部异步调用,因为角/区域猴子补丁websockets和setInterval等原因触发了更改检测。即使我没有与应用程序交互,我也经常看到一连串的变化检测,这有助于降低速度,尤其是在移动环境中。

这种默认行为可能很有用,但我现在使用Firebase的方式对何时需要更新视图有相当严格的控制,因此使用Firebase的回调方式将手动进行更改检测。

我知道为OnPush设置变更检测器策略会有帮助,我正在研究,但是我想从各个角度来攻击它。

我熟悉zone的runOutsideAngular,但现在不确定在这里应用它,因为所有异步调用都发生在Firebase模块中。

我怎样才能让Firebase完成它在角区域之外的所有业务?

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

代码语言:javascript
复制
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;
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-04 04:16:52

回想起来,这是显而易见的,但是仅仅实例化区域外的Firebase引用就可以了。例如:

代码语言:javascript
复制
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
    });
  }
}

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

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41455969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档