Angular:为整个类(服务或组件)禁用变更检测器

Sei*_*vic 2 typescript angular-services angular

如果通常导致更改检测运行的事件(setTimeout、setInterval、浏览器事件、ajax 调用等)来自特定类(服务或组件),是否有办法完全禁用 Angular 的更改检测器?

也就是说,当我发现setInterval在我的服务中注册导致全局更改检测每秒运行时,这对我来说似乎是完全错误的。

我知道我可以将我的代码包装在NgZone.runOutsideAngular方法的回调中,但我更喜欢可以为整个类禁用更改检测器的解决方案,因为我在服务中还有其他代码块也不必要地运行检测.

谢谢你的帮助。

yur*_*zui 6

一种可能的解决方案可能是@RunOutsideAngular为您的服务使用以下装饰器:

declare let Zone: any;

export function RunOutsideAngular(target: any) {
  Object.getOwnPropertyNames(target.prototype)
    .filter(p => typeof target.prototype[p] === 'function')
    .forEach(p => {
      let originalMethod = target.prototype[p];  
      target.prototype[p] = function (...args) {
        let self = this;
        Zone.root.run(() => originalMethod.apply(self, args));
      }
    });

  let ctor: any = function (...args) {
    let self = this;
    return Zone.root.run(() => target.apply(self, args));
  };
  ctor.prototype = target.prototype;
  return ctor;
}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例

如果您只想在某个类中禁用setTimeoutsetInterval您可以修补这些功能

function patchTimers(timers: any[]) {
    timers.forEach((timer) => {
        let originalMethod = window[timer];
        window[timer] = function (...args) {
            let self = this;
            if (Zone.current['__runOutsideAngular__'] === true && Zone.current.name === 'angular') {
                Zone.root.run(() => originalMethod.apply(self, args));
            } else {
                originalMethod.apply(this, arguments);
            }
        };
    })
}
patchTimers(['setTimeout', 'setInterval']);
Run Code Online (Sandbox Code Playgroud)

并像这样创建装饰器

export function RunOutsideAngular(target: any) {
    Object.getOwnPropertyNames(target.prototype)
        .filter(p => typeof target.prototype[p] === 'function')
        .forEach(p => {
            let originalMethod = target.prototype[p];
            target.prototype[p] = function (...args) {
                Zone.current['__runOutsideAngular__'] = true;
                originalMethod.apply(this, args);
                delete Zone.current['__runOutsideAngular__'];
            }
        });

    let ctor: any = function (...args) {
        Zone.current['__runOutsideAngular__'] = true;
        let instance = target.apply(this, args);
        delete Zone.current['__runOutsideAngular__'];
        return instance;
    };
    ctor.prototype = target.prototype;
    return ctor;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它如下

@RunOutsideAngular
export class Service {
  constructor() {
    setInterval(() => {
      console.log('ctor tick');
    }, 1000);
  }

  run() {
    setTimeout(() => {
      console.log('tick');
    }, 1000);

    setInterval(() => {
      console.log('tick interval');
    }, 1000)
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例


Jot*_*edo 5

您可以通过以下方式更改各个组件的检测策略:

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

@Component({
  selector: 'ws-layout-page',
  templateUrl: './layout-page.component.html',
  styleUrls: ['./layout-page.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LayoutPageComponent {

}
Run Code Online (Sandbox Code Playgroud)

我不知道有任何其他方法可以根据信息的来源实现某些选择性的打开/关闭