Before you can inject anything, you need to create a module and register your dependencies. You can do this in a separate file or in the same file as your React component.
If you haven't already, install the Universal Dependency Injection package:
npm install @universal-di/core
...and create a module:
const MY_TOKEN = new InjectionToken<string>("MY_TOKEN");
@Module({
providers: [{ provide: MY_TOKEN, useValue: "Hello world" }],
})
class AppModule {}
DIContextProvider
is a React context provider that allows you to provide dependencies to your React DOM.
const application = new DIApplication(AppModule);
<DIContextProvider injector={application.rootInjector}>
<ProductListComponent />
</DIContextProvider>;
useInjection
is a hook that allows you to inject dependencies into your React components.
export function ProductListComponent() {
// MY_TOKEN type is inferred here
const injectedString = useInjection(MY_TOKEN);
useEffect(() => {
console.log(injectedString);
}, []);
}