Dependency Injection (DI) Explained Simply
Understand what DI is, why Angular uses it, and how providers work in modern Angular.
Dependency Injection sounds scary, but it is just a clean way of giving your class the tools it needs. ## Real-world example Instead of a component creating its own service: - it would be stuck with one implementation - harder to test - harder to swap later With DI, Angular creates the service and gives it to your component. ## DI flow (picture) ```mermaid flowchart TD A[Angular Injector] --> B[Create UserService once] B --> C[Inject into HeaderComponent] B --> D[Inject into ProfileComponent] ``` ## Providers in modern Angular Most services use: `@Injectable({ providedIn: 'root' })` That means: - Angular creates one shared instance - available everywhere ## Advanced idea (quick mention) You can provide a service at a component level (new instance per component tree) but start with `root` until you have a reason. > Next: Routing, creating pages and navigation.