What is Dependency Injection?
Dependency Injection is a coding pattern in which a class receives its dependencies from an external provider rather than creating them internally. In Angular, this means your components don't need to know how to instantiate a service or manage its lifecycle; they simply 'ask' for it in their constructor. This promotes the 'Inversion of Control' (IoC) principle, making your code cleaner and easier to test.
- The @Injectable Decorator
To make a class available for injection, you must use the @Injectable() decorator. This tells Angular that this class can be managed by the DI system. The providedIn: 'root' property ensures the service is a singleton and allows for tree-shaking (removing the code if it's never used).
- The DI Hierarchy
Angular uses a hierarchical DI system. When a component requests a dependency, Angular first looks at the component's own providers, then its parent's, and so on, until it reaches the root. This allows you to have global singletons or 'sandboxed' service instances that only live within a specific feature module.
- Using Dependencies in Components
In Angular, you 'inject' a dependency by declaring it as a parameter in the class constructor. Angular's Injector looks at the type of the parameter and provides the correct instance.
DI Building Blocks Summary
| Term | Responsibility |
|---|---|
| Dependency | The object/service that a class needs to function. |
| Provider | The instruction on how to create/obtain the dependency. |
| Injector | The mechanism that finds or creates the dependency. |
| @Injectable | The decorator that makes a class 'available' for DI. |