Services, DI & Communication
Angular Dependency Injection
Dependency injection is Angular’s system for supplying a class with the objects it needs instead of having it construct them. You declare what you want in the constructor or with inject(), and Angular provides an instance.
What is Dependency Injection in Angular?
Dependency injection is Angular’s system for supplying a class with the objects it needs instead of having it construct them. You declare what you want in the constructor or with inject(), and Angular provides an instance.
Why Dependency Injection matters
DI is what makes Angular code testable and swappable. A component asking for JobService receives the real one in production and a mock in tests, with no change to the component.
Dependency Injection example
// constructor injection
export class JobListComponent {
constructor(private jobs: JobService, private router: Router) {}
}
// inject() — works in field initialisers, no constructor needed
export class JobListComponent {
private jobs = inject(JobService);
private router = inject(Router);
}Key points to remember
- Injectors form a hierarchy — Angular walks up until it finds a provider.
- Providing a service at component level gives each instance its own copy.
- useClass, useValue, useFactory and useExisting let you control what gets injected.
- InjectionToken supplies configuration values that have no class to inject.
Where a provider can be registered
| Scope | How | Instances |
|---|---|---|
| Application | @Injectable({ providedIn: "root" }) | one, shared everywhere |
| Application (config) | providers in app.config.ts | one, shared everywhere |
| Route | providers on a Route | one per lazy-loaded route |
| Component | providers in @Component | one per component instance |
Common mistakes with Dependency Injection
- Providing a service in a component by accident and losing shared state between components.
- A circular dependency between two services, which throws at startup.
Angular Dependency Injection— Interview Questions & FAQs
What is the difference between inject() and constructor injection?+
They do the same thing. inject() can be used in field initialisers and inside functions such as route guards, which makes it more flexible; constructor injection remains fine and is still widely used.
How do I inject a mock service in a test?+
Configure TestBed with providers: [{ provide: JobService, useValue: mockJobService }]. The component receives the mock without knowing anything changed.
