What is Dependency Injection in Angular: Simple Explanation and Example
dependencies. Instead of creating dependencies inside components, Angular injects them, making code easier to manage and test.How It Works
Imagine you need a coffee machine to make coffee, but instead of buying and maintaining it yourself, a coffee shop provides it for you whenever you need. Dependency injection in Angular works similarly: components ask for what they need, and Angular provides it automatically.
Angular has a special system called the injector that keeps track of all the services and objects your app needs. When a component or service asks for a dependency, the injector finds or creates it and hands it over. This way, components don’t have to know how to create or manage their dependencies, making the code cleaner and easier to change.
Example
This example shows a simple Angular service injected into a component. The service provides a greeting message, and the component uses it without creating the service itself.
import { Injectable, Component } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class GreetingService { getGreeting() { return 'Hello from the GreetingService!'; } } @Component({ selector: 'app-root', template: `<h1>{{ greeting }}</h1>` }) export class AppComponent { greeting: string; constructor(private greetingService: GreetingService) { this.greeting = this.greetingService.getGreeting(); } }
When to Use
Use dependency injection in Angular whenever your components or services need to use shared functionality like data fetching, logging, or configuration. It helps keep your code organized and testable by separating how things are created from how they are used.
For example, if multiple components need to get user data from a server, you create one user service and inject it wherever needed. This avoids repeating code and makes updates easier.
Key Points
- Dependency injection lets Angular provide needed services automatically.
- It improves code organization by separating creation from usage.
- Angular’s injector manages service lifetimes and sharing.
- It makes testing easier by allowing mock dependencies.