-
-
Notifications
You must be signed in to change notification settings - Fork 932
/
use-injector.ts
34 lines (33 loc) · 1.03 KB
/
use-injector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { ProviderToken } from '@angular/core';
import { useContext } from 'react';
import { HostedComponentContext } from '../directives/react-component-host.directive';
/**
* @description
* Exposes the Angular injector which allows the injection of services into React components.
*
* @example
* ```ts
* import { useInjector } from '\@vendure/admin-ui/react';
* import { NotificationService } from '\@vendure/admin-ui/core';
*
* export const MyComponent = () => {
* const notificationService = useInjector(NotificationService);
*
* const handleClick = () => {
* notificationService.success('Hello world!');
* };
* // ...
* return <div>...</div>;
* }
* ```
*
* @docsCategory react-hooks
*/
export function useInjector<T = any>(token: ProviderToken<T>): T {
const context = useContext(HostedComponentContext);
const instance = context?.injector.get(token);
if (!instance) {
throw new Error(`Could not inject ${(token as any).name ?? token.toString()}`);
}
return instance;
}