我正在尝试在节点中使用
angular/zone.js编写一个简单的演示,但由于某种原因,没有调用beforeTask或afterTask.
这是我正在运行的代码:
require('zone.js');
function foo () {
Zone.current.fork({
name: 'foo_zone',
beforeTask: function () {
console.log('~~~ ZONE START ~~~');
},
afterTask: function () {
console.log('~~~ ZONE END ~~~');
}
})
.run(function () {
console.log('in the zone');
console.log('Zone.current.name', Zone.current.name); // prints foo_zone
setTimeout(() => {
console.log('timeout is up');
}, 1000);
});
}
foo();
现在在区域内,所有打印都很好,包括区域名称,但都没有调用任何钩子.
我是否遗漏了zone.js node.js的基本内容?
(使用节点v5.0.0运行,zone.js 0.6.23)
最佳答案 这是示例存储库.
https://github.com/JiaLiPassion/zone-node
首先,您需要使用最新版本的zone.js
要在nodejs中使用zone.js,您应该要求zone-node.js,
以下是正在运行的示例.
require('./zone-node.js');
function log(str) {
Zone.root.run(function() {
console.log(str);
});
}
function foo() {
Zone.current.fork({
name: 'fooZone',
onScheduleTask: function(delegate, curr, target, task) {
log('Zone begin to schedule task not async yet ' + task.source);
return delegate.scheduleTask(target, task);
},
onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
log('~~~~Zone before invoke async callback~~~~' + task.source);
delegate.invokeTask(target, task, applyThis, applyArgs);
log('~~~~Zone after invoke async callback~~~~' + task.source);
},
}).run(function() {
log('current zone, ' + Zone.current.name);
setTimeout(function() {
log('timeout is up, ', Zone.current.name);
}, 100);
});
};
foo();
在nodejs中运行后,输出将是.
current zone, fooZone
Zone begin to schedule task not async yetsetTimeout
~~~~Zone before invoke async callback~~~~setTimeout
timeout is up,
~~~~Zone after invoke async callback~~~~setTimeout