Angular Dependency Injection
Angular Dependency Injection is a design pattern used to provide required dependencies such as services to components and other Angular classes without creating those objects manually.
What is Dependency Injection?
Dependency Injection, commonly called DI, is a mechanism through which Angular provides an object required by another class.
Instead of creating a service manually using new, a component asks Angular for that service and Angular's injector resolves and provides it.
Simple Definition
Dependency Injection means Angular creates and provides the required dependency for the component.
Dependency Injection Flow
Main Dependency Injection Concepts
Dependency
The service or object required by another class.
CourseService
Injector
Responsible for resolving and providing dependencies.
Injector
Provider
Defines how Angular should create or provide a dependency.
Provider
Reusable Services
Services can be injected into multiple components.
Reuse
1. Basic Dependency Injection Example
A component can receive a service through constructor injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourseName(): string {
return 'Angular Full Stack';
}
}
import { Component } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course',
templateUrl: './course.component.html'
})
export class CourseComponent {
constructor(
private courseService: CourseService
) {
}
}
How it works
The component declares CourseService as a constructor dependency. Angular resolves the service and provides it to the component.
2. Constructor Injection
Constructor injection is a common way of receiving dependencies inside Angular classes.
constructor(
private trainingService: TrainingService
) {
}
3. Why Use Dependency Injection?
Reusability
The same service can be used by different components.
Reuse
Loose Coupling
Components depend on abstractions and provided services rather than creating objects themselves.
Decoupled
Testability
Dependencies can be replaced or mocked during testing.
Testing
Centralized Creation
Angular manages dependency creation and resolution.
Injector
4. Manual Object Creation vs Dependency Injection
export class CourseComponent {
courseService =
new CourseService();
}
constructor(
private courseService: CourseService
) {
}
Key Difference
With Dependency Injection, the component does not need to create the service instance itself. Angular's injector manages the dependency.
5. The @Injectable Decorator
The @Injectable() decorator marks a class as available for Angular's dependency injection system.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TrainingService {
getInstituteName(): string {
return 'CIIT Training Institute';
}
}
Service: TrainingService
Provider: Root Injector
6. What is a Provider?
A provider tells Angular how a dependency should be created or supplied when a class requests it.
Class Provider
Provides an instance of a class.
useClass
Value Provider
Provides a predefined value.
useValue
Factory Provider
Uses a factory function to create a value.
useFactory
Existing Provider
Reuses an existing dependency.
useExisting
7. What is an Injector?
The injector is responsible for resolving dependencies and returning the appropriate object to the class that requested it.
Component
|
↓
Requests CourseService
|
↓
Angular Injector
|
↓
Resolves Provider
|
↓
CourseService Instance
|
↓
Component Receives Service
Simple Idea
The injector acts like a dependency manager between the component and the services it needs.
8. Injecting Multiple Dependencies
A component can request more than one dependency through its constructor.
constructor(
private courseService: CourseService,
private notificationService:
NotificationService,
private trainingService:
TrainingService
) {
}
9. Root Dependency Injection
Services configured with providedIn: 'root' can be resolved through the application's root injector.
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourses(): string[] {
return [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET'
];
}
}
10. Component-Level Provider
A service can also be provided inside a component's providers configuration when a more localized scope is required.
@Component({
selector: 'app-dashboard',
providers: [
CourseStateService
],
templateUrl: './dashboard.component.html'
})
export class DashboardComponent {
constructor(
private courseStateService:
CourseStateService
) {
}
}
When to Use
Component-level providers are useful when service state should be associated with a particular component hierarchy.
11. Dependency Injection with ngOnInit()
A component can inject a service through its constructor and then use that service during initialization.
constructor(
private trainingService: TrainingService
) {
}
ngOnInit(): void {
this.courses =
this.trainingService.getCourses();
}
12. Dependency Injection and Testing
Dependency Injection makes components easier to test because dependencies can be replaced with test implementations or mocks.
constructor(
private courseService: CourseService
) {
}
Testing Benefit
During testing, the component can work with a controlled replacement for CourseService instead of depending on the real implementation.
Complete CIIT Training Institute Example
Suppose the CIIT Training Institute dashboard needs course data and notification functionality. Both services can be injected into the dashboard component.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseService {
getCourses(): string[] {
return [
'Java Full Stack',
'Python Full Stack',
'Full Stack .NET',
'Data Analytics'
];
}
}
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
showMessage(message: string): void {
console.log(message);
}
}
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent
implements OnInit {
courses: string[] = [];
constructor(
private courseService:
CourseService,
private notificationService:
NotificationService
) {
}
ngOnInit(): void {
this.courses =
this.courseService.getCourses();
this.notificationService.showMessage(
'CIIT Dashboard Loaded'
);
}
}
<h2>
CIIT Training Institute
</h2>
<h4>
Available Courses
</h4>
<ul>
<li *ngFor="let course of courses">
{{ course }}
</li>
</ul>
CIIT Training Institute
- Java Full Stack
- Python Full Stack
- Full Stack .NET
- Data Analytics
Notification: CIIT Dashboard Loaded
Dependency Injection Quick Reference
| Concept | Purpose | Example |
|---|---|---|
| Dependency | Object required by a class |
CourseService
|
| Injector | Resolves and provides dependencies |
Injector
|
| Provider | Defines how dependency is supplied |
providedIn
|
| Injectable | Marks service for dependency injection |
@Injectable()
|
| Constructor Injection | Receives dependency in class constructor |
constructor(...)
|
Advantages of Dependency Injection
- Makes application components easier to organize.
- Encourages reusable service-based functionality.
- Reduces direct object creation inside components.
- Supports separation of responsibilities.
- Makes dependencies explicit and easier to understand.
- Helps improve testability through replaceable dependencies.
Dependency Injection Best Practices
- Prefer Angular Dependency Injection instead of manually creating service instances.
- Keep services focused on reusable responsibilities.
- Use meaningful service names and constructor parameters.
- Choose service scope based on the application's sharing needs.
- Avoid injecting unnecessary dependencies into components.
- Use dependency injection to keep components easier to test and maintain.
Summary
Angular Dependency Injection allows components and other classes to receive required services from Angular's injector instead of creating those services manually.
Important concepts include Dependencies, Injectors, Providers, @Injectable() and Constructor Injection.