diff --git a/lib/zone.ts b/lib/zone.ts index 522b56fd3..455c29c54 100644 --- a/lib/zone.ts +++ b/lib/zone.ts @@ -257,6 +257,13 @@ interface ZoneType { * Verify that Zone has been correctly patched. Specifically that Promise is zone aware. */ assertZonePatched(); + + /** + * Run function outside current zone, instead it will run under rootZone. + */ + runOutsideOfCurrentZone( + callback: Function, applyThis?: any, applyArgs?: any, source?: string, runGuarded?: boolean, + zoneSpec?: ZoneSpec): T; } /** @@ -564,6 +571,27 @@ const Zone: ZoneType = (function(global: any) { } } + static get rootZone(): AmbientZone { + let zone = Zone.current; + while (zone.parent) { + zone = zone.parent; + } + return zone; + } + + static runOutsideOfCurrentZone( + callback: Function, applyThis?: any, applyArgs?: any, source?: string, + runGuarded: boolean = true, zoneSpec?: ZoneSpec) { + let zone = Zone.rootZone; + if (zoneSpec) { + zone = zone.fork(zoneSpec); + } + if (runGuarded) { + return zone.runGuarded(callback, applyThis, applyArgs, source); + } else { + return zone.run(callback, applyThis, applyArgs, source); + } + } static get current(): AmbientZone { return _currentZoneFrame.zone; diff --git a/test/common/zone.spec.ts b/test/common/zone.spec.ts index 258f100ee..f6b63ee5b 100644 --- a/test/common/zone.spec.ts +++ b/test/common/zone.spec.ts @@ -83,6 +83,24 @@ describe('Zone', function() { }); }); + describe('run out side of current zone', function() { + it('should be able to get run under rootZone', function() { + Zone.current.fork({name: 'testZone'}).run(function() { + Zone.runOutsideOfCurrentZone(() => { + expect(Zone.current.name).toEqual(''); + }); + }); + }); + + it('should be able to get run outside of current zone', function() { + Zone.current.fork({name: 'testZone'}).run(function() { + Zone.runOutsideOfCurrentZone(() => { + expect(Zone.current.name).toEqual('newTestZone'); + expect(Zone.current.parent.name).toEqual(''); + }, null, null, null, true, {name: 'newTestZone'}); + }); + }); + }); describe('get', function() { it('should store properties', function() {