0
# Core Zone API
1
2
Zone creation, execution context management, and basic zone operations for maintaining execution state across asynchronous boundaries.
3
4
## Capabilities
5
6
### Global Zone Constructor
7
8
The global Zone constructor provides access to the current zone, root zone, and zone management utilities.
9
10
```typescript { .api }
11
/**
12
* Global Zone constructor interface accessible via global Zone constant
13
*/
14
interface ZoneType {
15
/** Current active zone - changes when zones are forked and run */
16
readonly current: Zone;
17
18
/** Current executing task, null if no task is running */
19
readonly currentTask: Task | null;
20
21
/** Root zone - the top-level zone from which all others inherit */
22
readonly root: Zone;
23
24
/** Verify that Zone has been correctly patched */
25
assertZonePatched(): void;
26
27
/** Load a patch for specified native module */
28
__load_patch(name: string, fn: PatchFn, ignoreDuplicate?: boolean): void;
29
30
/** Generate zone symbol with prefix */
31
__symbol__(name: string): string;
32
}
33
```
34
35
### Zone Interface
36
37
Individual zone instances provide execution context management and child zone creation.
38
39
```typescript { .api }
40
/**
41
* Zone interface for execution context management
42
*/
43
interface Zone {
44
/** Parent zone reference, null for root zone */
45
readonly parent: Zone | null;
46
47
/** Zone name for debugging and identification */
48
readonly name: string;
49
50
/** Get property value from this zone or parent zones */
51
get(key: string): any;
52
53
/** Find zone in the parent chain that has the specified property */
54
getZoneWith(key: string): Zone | null;
55
56
/** Create a child zone with the given specification */
57
fork(zoneSpec: ZoneSpec): Zone;
58
59
/** Wrap a callback to run in this zone's context */
60
wrap<F extends Function>(callback: F, source: string): F;
61
62
/** Execute function in this zone's context */
63
run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
64
65
/** Execute function in this zone with error handling */
66
runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
67
68
/** Execute the Task by restoring the zone context */
69
runTask<T>(task: Task, applyThis?: any, applyArgs?: any): T;
70
71
/** Schedule a MicroTask in this zone */
72
scheduleMicroTask(source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void): MicroTask;
73
74
/** Schedule a MacroTask in this zone */
75
scheduleMacroTask(source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void, customCancel?: (task: Task) => void): MacroTask;
76
77
/** Schedule an EventTask in this zone */
78
scheduleEventTask(source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void, customCancel?: (task: Task) => void): EventTask;
79
80
/** Schedule an existing Task */
81
scheduleTask<T extends Task>(task: T): T;
82
83
/** Cancel a scheduled Task */
84
cancelTask(task: Task): any;
85
}
86
```
87
88
**Usage Examples:**
89
90
```typescript
91
import 'zone.js';
92
93
// Access current zone
94
console.log('Current zone:', Zone.current.name); // '<root>'
95
96
// Create child zone with properties
97
const userZone = Zone.current.fork({
98
name: 'user-context',
99
properties: {
100
userId: 123,
101
requestId: 'req-456'
102
}
103
});
104
105
// Run code in zone context
106
userZone.run(() => {
107
console.log('Zone name:', Zone.current.name); // 'user-context'
108
console.log('User ID:', Zone.current.get('userId')); // 123
109
110
// Nested zone
111
const requestZone = Zone.current.fork({
112
name: 'request-handler',
113
properties: { step: 'processing' }
114
});
115
116
requestZone.run(() => {
117
// Can access parent zone properties
118
console.log('User ID:', Zone.current.get('userId')); // 123
119
console.log('Step:', Zone.current.get('step')); // 'processing'
120
});
121
});
122
```
123
124
### Zone Property Management
125
126
Zones maintain a hierarchy where child zones inherit properties from parent zones.
127
128
```typescript { .api }
129
/**
130
* Get property value from this zone or parent zones
131
* @param key - Property key to retrieve
132
* @returns Property value or undefined if not found
133
*/
134
get(key: string): any;
135
136
/**
137
* Find zone in the parent chain that has the specified property
138
* @param key - Property key to search for
139
* @returns Zone that contains the property or null if not found
140
*/
141
getZoneWith(key: string): Zone | null;
142
```
143
144
**Usage Examples:**
145
146
```typescript
147
const parentZone = Zone.current.fork({
148
name: 'parent',
149
properties: { theme: 'dark', version: '1.0' }
150
});
151
152
const childZone = parentZone.fork({
153
name: 'child',
154
properties: { component: 'button' }
155
});
156
157
childZone.run(() => {
158
// Child zone can access parent properties
159
console.log(Zone.current.get('theme')); // 'dark' (from parent)
160
console.log(Zone.current.get('component')); // 'button' (from child)
161
162
// Find which zone has a property
163
const themeZone = Zone.current.getZoneWith('theme');
164
console.log(themeZone?.name); // 'parent'
165
});
166
```
167
168
### Zone Execution Context
169
170
Zones preserve execution context across synchronous and asynchronous operations.
171
172
```typescript { .api }
173
/**
174
* Execute function in this zone's context
175
* @param callback - Function to execute
176
* @param applyThis - 'this' context for the function
177
* @param applyArgs - Arguments to pass to the function
178
* @param source - Debug identifier for the operation
179
* @returns Return value from the callback function
180
*/
181
run<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
182
183
/**
184
* Execute function in this zone with automatic error handling
185
* @param callback - Function to execute
186
* @param applyThis - 'this' context for the function
187
* @param applyArgs - Arguments to pass to the function
188
* @param source - Debug identifier for the operation
189
* @returns Return value from the callback function
190
*/
191
runGuarded<T>(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): T;
192
193
/**
194
* Wrap a callback to run in this zone's context when invoked
195
* @param callback - Function to wrap
196
* @param source - Debug identifier for the operation
197
* @returns Wrapped function that will execute in this zone
198
*/
199
wrap<F extends Function>(callback: F, source: string): F;
200
```
201
202
**Usage Examples:**
203
204
```typescript
205
const myZone = Zone.current.fork({ name: 'myZone' });
206
207
// Direct execution
208
const result = myZone.run(() => {
209
console.log('Running in:', Zone.current.name); // 'myZone'
210
return 42;
211
}); // result = 42
212
213
// Wrapped callback execution
214
const wrappedCallback = myZone.wrap(() => {
215
console.log('Wrapped callback in:', Zone.current.name);
216
}, 'wrapped-callback');
217
218
// Later invocation maintains zone context
219
setTimeout(wrappedCallback, 100); // Will run in 'myZone'
220
221
// Error handling with runGuarded
222
myZone.runGuarded(() => {
223
throw new Error('Test error');
224
// Error will be handled by zone's error handling mechanism
225
});
226
```
227
228
### Zone Symbol API
229
230
Zone provides a symbol generation API for creating unique identifiers.
231
232
```typescript { .api }
233
/**
234
* Generate zone symbol with __zone_symbol__ prefix
235
* @param name - Base name for the symbol
236
* @returns Prefixed symbol string
237
*/
238
__symbol__(name: string): string;
239
```
240
241
**Usage Examples:**
242
243
```typescript
244
// Generate zone symbols
245
const eventSymbol = Zone.__symbol__('addEventListener');
246
console.log(eventSymbol); // '__zone_symbol__addEventListener'
247
248
// Used internally for patching
249
const originalMethod = window[Zone.__symbol__('originalMethod')];
250
```