To avoid losing scope during asynchronous execution, you need to import zone.js at the application entry point.
// entry.ts
import 'zone.js';
and you have to transform native async/await
expressions to generators using Babel
(details).
If zone.js
is not used, a fallback implementation will be used, which may lead to losing context during asynchronous execution.
export class ExampleContext extends ScopeContextBase {
private static _scope_internal: Scope<ExampleContext>;
private static get scope() {
return (ExampleContext._scope_internal ??= new Scope<ExampleContext>(
'ExampleContext'
));
}
get parent(): ExampleContext | null {
return ExampleContext.scope.getByContext(this)?.parent?.context ?? null;
}
static get current(): ExampleContext | null {
return ExampleContext.scope.context ?? null;
}
static create(context: ExampleContext | null): IScopeInstance<ExampleContext> {
return ExampleContext.scope.create(context);
}
}
const ctx = new ExampleContext();
await ExampleContext.create(ctx).run(async () => {
ExampleContext.current === ctx; // true
});
Generated using TypeDoc