我正在尝试实现简单的zone.afterTask和beforeTask挂钩,但是尽管代码没有抛出任何错误,但这些方法永远不会被调用。
我搜索了区域github中的回购,除了在示例中使用的方法之外,在源代码中找不到对这些方法的任何引用。计数实例确实使用了afterTask和beforeTask,但是我已经设置了调试器,并且在它们的示例中也没有调用这些方法。
看起来这些方法已经被废弃了,,如果不是的话,请告诉我我做错了什么。
这是我的密码-
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));
}
}发布于 2016-04-26 09:36:25
我认为对于您的用例,您可以利用onInvokeTask和onHasTask挂钩,如下所述:
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。
https://stackoverflow.com/questions/36857742
复制相似问题