Angular has a wrapper class for Zone.js called ngZone. You can inject it into your component like any service.
constructor(private zone: NgZone) {
this.zone.run(() => { console.log('This is zone'});
}
However, with this approach, we cannot use the full functionality of zone.js. For that, we have to declare:
declare let Zone: any;
public class MyComponent {
constructor() {
Zone.current.fork({
name: 'myZone'
}).run(() => {
console.log('in myzone? ', Zone.current.name);
});
}
}
Also, the APIs have changed since v 0.6.0. For running beforeTask and afterTask, you can look about it here, however, I looked into it and was unable to find anything related to beforeTask and afterTask.
Updated
For running beforeTask and afterTask, this is how it is possible in the new API.
constructor() {
const parentZone = new Zone();
const childZone = parentZone.fork({
name: 'child',
onInvoke: (...args) => {
console.log('invoked\n', args);
const valueToReturn = args[3](); // Run the function provided in the Zone.run
console.log('after callback is run');
return valueToReturn;
}
});
console.log(childZone.run(() => {console.log('from run'); return 'from child run';}));
}
NOTE:
If you want to create a scheduleMicroTask and want to have same functionality in it also, then you will need to implement onInvokeTask and/or onScheduleTask in the ZoneSpec (inside the parentZone.fork()).
constructor() {
const parentZone = new Zone();
const childZone = parentZone.fork({
name: 'child',
onScheduleTask: (...args) => {
console.log('task schedule...\n', args);
return args[3];
},
onInvokeTask: (...args) => {
console.log('task invoke...\n', args);
return args[3].callback();
}
});
const microTask = childZone
.scheduleMicroTask(
'myAwesomeMicroTask',
() => {
console.log('microTask is running');
return 'value returned from microTask';
} );
console.log(microTask.invoke());
}