Firebase使用了许多内部异步调用,因为角/区域猴子补丁websockets和setInterval等原因触发了更改检测。即使我没有与应用程序交互,我也经常看到一连串的变化检测,这有助于降低速度,尤其是在移动环境中。
这种默认行为可能很有用,但我现在使用Firebase的方式对何时需要更新视图有相当严格的控制,因此使用Firebase的回调方式将手动进行更改检测。
我知道为OnPush设置变更检测器策略会有帮助,我正在研究,但是我想从各个角度来攻击它。
我熟悉zone的runOutsideAngular,但现在不确定在这里应用它,因为所有异步调用都发生在Firebase模块中。
我怎样才能让Firebase完成它在角区域之外的所有业务?
编辑:显示问题的示例代码:
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;
}
}发布于 2017-01-04 04:16:52
回想起来,这是显而易见的,但是仅仅实例化区域外的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
});
}
}通过将断点放在组件中,我能够将所有更改检测周期追溯到实例化Firebase引用的那一行,这意味着在区域外运行它将阻止它们。
请注意,如果您走这个路线,您必须确保更改检测是在必要时触发的。有关示例,请参见https://stackoverflow.com/a/34829089/458614。
https://stackoverflow.com/questions/41455969
复制相似问题