Angular 2,使用带有requestAnimationFrame循环的ngZone.runOutsideAngular

时间:2017-05-11 10:49:40

标签: angular requestanimationframe

根据我在线阅读的内容,Angular团队建议您始终在Angular区域之外调用requestAnimationFrame(),如下所示:

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp || new Date().getTime();
    this.myAnimeMethod(timestamp);
  });
});

但循环呢......

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp;
    this.myAnimeMethod(timestamp, timerStart);
  });
});

myAnimeMethod(timestamp, timerStart) {
  let time = timestamp || new Date().getTime();
  let runtime = time - timerStart;

  /// animation logic here

  if(runtime < 10000) {

    // ------- continue to animate for 10 seconds -- //

    requestAnimationFrame(timestamp => {
      this.myAnimeMethod(timestamp, timerStart);
    });
  }
}

是否足以在第一次请求时拨打this.ngZone.runOutsideAngular(),或者我应该在this.ngZone.runOutsideAngular()内再次拨打myAnimeMethod()这样的话?

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp;
    this.myAnimeMethod(timestamp, timerStart);
  });
});

myAnimeMethod(timestamp, timerStart) {
  let time = timestamp || new Date().getTime();
  let runtime = time - timerStart;

  /// animation logic here

  if(runtime < 10000) {

    // ------- request to run outside of Angular again while continuing to animate for 10 seconds -- //

    this.ngZone.runOutsideAngular(() => {
      requestAnimationFrame(timestamp => {
        this.myAnimeMethod(timestamp, timerStart);
      });
    });

  }
}

2 个答案:

答案 0 :(得分:0)

简短回答:您无需继续从来自Angular以外的电话的order处理程序中调用NgZone.runOutsideAngular

答案很长:一旦你进入“root”区域(这是你拨打requestAnimationFrame时得到的),除非你明确要求,否则任何NgZone.runOutsideAngular回调也将从该区域运行不同的区域,例如通过requestAnimationFrame

要检查这一点,请尝试从NgZone.run处理程序中调用静态函数NgZone.isInAngularZone()

请注意,我使用Angular 4.4.4和Zone.js 0.8.18进行了测试。

答案 1 :(得分:0)

您还可以创建一个ngzon-flags.ts,在其中放置所有异常以进行更改检测。

// All events inside the BLACK-LIST Array will not trigger updates anymore from angular
// requestAnimationFrame wont trigger change detection
(window as any).__Zone_disable_requestAnimationFrame = true; 
// Same for scroll and mousemove or any other event youll add
(window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove'];

将该文件导入到您的polyfills.ts:

import './ngzone-flags'