Dependency Injection Tricks in Angular
Jun 4, 2020 10:31 · 243 words · 2 minute read
Here are few tricks that I picked up along the way in everyday Angular use and study. Along with usual provideIn:{} and dependency injection from documentation examples, there is as usual - more to the story.
Providing dependencies - the alternate ways.
Declaring the suspects:
- A service that will be the dependency we are injecting: LoggerService
- Parent component that will provide service
- Directive: ProvideDirective that will also provide aforementioned service.
- Child component that will use the service which will be provided to it in 2 different ways.
Ok with that out ot the way let us start:
Declaring LoggerService
Nothing much here just a simple service that logs stuff.
Component that will provide service
Inside providers: [LoggerService]
we will provide service so it can be injected in this components children later.
Directive that also provides the service
This directive will be attached to component later and thus the component will also have access to the service.
Child component consuming the dependencies
The Gist above just injects the service and it has no idea who is providing it. It also injects parent component so we can log it later in our message.
Putting it in action
Here we can see <dep-child-comp>
appearing two times and no errors. The service is provided in both cases. In first case it is provided by the parent component
and in the last from attached directive.