Skip to content

Commit cfb558c

Browse files
committed
feat(core): add injectLazy to injection.ts
1 parent 039fd19 commit cfb558c

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

packages/core/src/injection.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,31 @@ export function injectRef<T>(
4242
) as T;
4343
}
4444

45+
/**
46+
* Inject a dependency lazily loaded as a promise.
47+
*
48+
* @param token promise of the token to inject
49+
* @param injector injector to use to instantiate the dependency
50+
* @returns promise of the dependency instance
51+
*
52+
* @example
53+
* ```ts
54+
* private myService = injectLazy(import('./my-service').then(m => m.MyService));
55+
* ```
56+
* ```ts
57+
* async someMethod() {
58+
* const service = await this.myService;
59+
* service.doSomething();
60+
* }
61+
* ```
62+
*/
63+
export async function injectLazy<T>(
64+
token: Promise<ProviderToken<T>>,
65+
injector = inject(Injector),
66+
): Promise<T> {
67+
return token.then((t) => injector.get(t));
68+
}
69+
4570
/**
4671
* Return a function that accepts another function.
4772
* The accepted function will be executed synchronously in the

0 commit comments

Comments
 (0)