zone.afterTask 和 zone.beforeTask 挂钩方法不起作用

zone.afterTask and zone.beforeTask hook methods not working

我正在尝试实现简单的 zone.afterTaskbeforeTask 挂钩,但是尽管 code 没有抛出任何错误,但这些方法永远不会被调用.

我搜索了 Zone repo in github , and couldn't find any reference to these methods in the source code apart from the ones that's used in the example. counting example 确实使用了 afterTaskbeforeTask,但我设置了一个调试器,发现这些方法在他们的示例中也从未被调用。

看起来这些方法已被弃用,如果不是,请告诉我我做错了什么。

这是我的代码 -

import { Component } from 'angular2/core';

@Component({
  template: `
      <div>
        <p>Basic use of Zone</p>
        <button (click)="startTask()">Start Task</button>
        <p> Time taken {{timeTaken}}</p>
      </div>
    `
})
export class HelloZone {
  timeTaken: any;

  task1(){
    for (let i = 0; i < 1e5; i++);
  }

  startTask() {
    let startTime;

    let myZone = Zone.parent.fork({
      beforeTask: function() {
        startTime = new Date();
      },
      afterTask: function() {
        this.timeTaken = new Date() - startTime;
      }
    });
    myZone.run(function(){
      this.task1();
      setTimeout(this.task1, 2000);
      this.task1();
    }.bind(this));
  }
}

我认为对于您的用例,您可以利用 onInvokeTaskonHasTask 挂钩,如下所述:

export class HelloZone {
  timeTaken: any;

  constructor(private zone:NgZone) {

  }

  (...)

  startTask() {
    let startTime;

    let myZone = Zone.current.fork({
      onInvokeTask: (parent, current, target, task) => {
        startTime = new Date();
        parent.invokeTask(target, task);
      },
      onHasTask: (parent, current, target, hasTask) => {
        if (!hasTask.macroTask) {
          this.zone.run(() => {
            this.timeTaken = new Date() - startTime;
          });
        }
      }
    });
    myZone.run(() => {
      this.task1();
      setTimeout(this.task1, 2000);
      this.task1();
    });
  }
}

看到这个 plunkr:https://plnkr.co/edit/EH8uy66ke1i61QhE9fYi?p=preview