Skip to content

Commit 7344f8e

Browse files
committed
feat(core): add useInjectionContext function
1 parent e89f3d2 commit 7344f8e

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

packages/core/src/injection.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import { inject, Injector, ProviderToken } from '@angular/core';
1+
import {
2+
inject,
3+
Injector,
4+
ProviderToken,
5+
runInInjectionContext,
6+
} from '@angular/core';
27

38
/**
49
* Inject a proxy of the target dependency, which defers the actual injection
@@ -36,3 +41,21 @@ export function injectRef<T>(
3641
},
3742
) as T;
3843
}
44+
45+
/**
46+
* Return a function that accepts another function.
47+
* The accepted function will be executed synchronously in the
48+
* current injection context, and its return value will be forwarded.
49+
*
50+
* @example
51+
* ```ts
52+
* private inContext = useInjectionContext();
53+
* ```
54+
* ```ts
55+
* const result = inContext(() => inject(MyService).doSomething());
56+
* ```
57+
*/
58+
export const useInjectionContext =
59+
(injector = inject(Injector)) =>
60+
<T>(fn: () => T): T =>
61+
runInInjectionContext(injector, fn);

0 commit comments

Comments
 (0)