This code has been taken from the web components dependency injection article, published by Manuel Rauber and Yannick Baron. You can find their github repository here and github profiles Manuel Rauber and Yannick Baron.
Considering your web component tree looks like this:
<my-root>
<my-child></my-child>
</my-root>
// my-root.component.js
import { ContainerProvider } from "wc-dependency-injection";
import { Logger } from "@services/logger.service.ts";
@ContainerProvider([{ provide: Logger, useClass: Logger }])
export class MyRoot extends HTMLElement {
// ...
}
// my-child.component.js
import { Inject } from "wc-dependency-injection";
export class MyChild extends HTMLElement {
@Inject() logger: Logger;
connectedCallback() {
this.logger.log("Hello World!");
}
}
npm install wc-dependency-injection
If you want to contribute to this library - you are very welcome! Please create a pull request and describe the changes you made and which problem it solves.
MIT