Dependency Injection (DI) is the architectural pattern that powers Angular. It's how components receive the tools they need to function without knowing how those tools are created.
1The Singleton Pattern
In Angular, most services are singletons. When you provide a service in the 'root', Angular creates one single instance of that class the first time it is requested. Every subsequent component that asks for that service receives a reference to that same exact instance. This is incredibly powerful for state management: if you store a user's profile in a service, every component in your app can access and update that same data in real-time.
2Why DI Matters
Without DI, your components would be 'tightly coupled' to their dependencies. If a component creates its own ApiService using new, you can't easily swap that service out for a 'Mock' version during testing. With DI, the component simply says 'I need something that looks like an ApiService', and Angular provides it. This makes your code modular, flexible, and extremely easy to test.
