1

Here's the code demonstrating zone.js capabilities from here:

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);

The above will log:

'in the zone: false'

'in the zone: true'

I don't really understand what is it that zone is doing here and how's it related to intercepting events that this video talks about.

It outputs false the first time because Zone.current.inTheZone is undefined, and since we changed Zone.current.inTheZone = true; that is the value now that is ouputted second time. What's special is zone doing here?

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

2

Zone allows you to persist some properties across the asynchronous operations encapsulated within the zone. So basically here it shows that there's no inTheZone property attached to the current zone. But when you executed zone.fork().run() the callback is executed in the new forked zone and the async task setTimeout will be executed in this forked zone as well. And you will get the inTheZone property inside this zone but it won't be accessible in other zones. Here is probably a better example:

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);

As you can see there are two async tasks here. And the setTimeout from the current zone will be executed earlier than the timeout from the forked zone. The run() is synchrounous so inTheZone should be set to true before the first setTimetout is executed. But it's logged as false because the current zone can't access the property from the forked zone.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488