下面的代码演示了来自zone.js的这里功能
Zone.current.fork({}).run(function () {
Zone.current.inTheZone = true;
setTimeout(function () {
console.log('in the zone: ' + !!Zone.current.inTheZone);
}, 0);
});
console.log('in the zone: ' + !!Zone.current.inTheZone);以上将记录:
'in the zone: false'
'in the zone: true'我真的不明白这个区域在这里做什么,以及它与这段视频谈论的拦截事件有什么关系。
它第一次输出false,因为Zone.current.inTheZone是undefined,而且由于我们更改了Zone.current.inTheZone = true;,所以现在是第二次输出的值。zone在这里有什么特别的?
发布于 2017-07-29 17:21:42
区域允许您在封装在区域中的异步操作中持久化某些属性。因此,基本上在这里,它表明没有附加到当前区域的inTheZone属性。但是,当您执行zone.fork().run()时,回调将在新的分叉区域中执行,异步任务setTimeout也将在这个分叉区域执行。您将在此区域中获得inTheZone属性,但在其他区域中不能访问它。这里可能有一个更好的例子:
Zone.current.fork({}).run(function () {
Zone.current.inTheZone = true;
setTimeout(function () {
console.log('in the zone: ' + !!Zone.current.inTheZone); // true
}, 2000);
});
setTimeout(function () {
console.log('in the zone: ' + !!Zone.current.inTheZone); // false
}, 1000);如您所见,这里有两个异步任务。并且来自当前区域的setTimeout将比分叉区域的超时执行得更早。run()是同步的,因此在执行第一个setTimetout之前,应该将inTheZone设置为true。但是它被记录为false,因为当前区域无法从分叉区域访问该属性。
https://stackoverflow.com/questions/40531025
复制相似问题