Injecting Dependencies
Angular allows a component or service to receive the objects it needs through Dependency Injection. Instead of creating those objects manually, Angular provides them through its injector.
What Does Injecting a Dependency Mean?
A dependency is an object required by another class to perform some operation.
Injecting a dependency means asking Angular to provide that object instead of creating the object directly with new.
Simple Definition
Dependency Injection allows a class to receive the object it needs from Angular rather than creating that object itself.
Dependency Injection Flow
Common Dependency Injection Approaches
Constructor Injection
Declare the required dependency in the constructor.
constructor(...)
inject()
Obtain a dependency using Angular's inject function.
inject()
Provider
Defines how Angular should provide a dependency.
providers
Injector Hierarchy
Angular resolves dependencies through its injector hierarchy.
Injector
1. Constructor Injection
Constructor injection is a common approach where a service is declared as a constructor parameter.
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
Angular sees that CourseComponent requires CourseService and asks the injector to resolve that dependency.
2. Using the Injected Dependency
Once a service has been injected, the component can call its methods through the injected property.
courseName = '';
constructor(
private courseService: CourseService
) {
}
loadCourse(): void {
this.courseName =
this.courseService.getCourseName();
}
<button
class="btn btn-primary"
(click)="loadCourse()">
Load Course
</button>
<p>
Course:
{{ courseName }}
</p>
Course: Angular Full Stack
3. Injecting Multiple Dependencies
A component can request multiple services when it needs functionality from different parts of the application.
constructor(
private courseService: CourseService,
private trainingService: TrainingService,
private notificationService:
NotificationService
) {
}
4. Using inject()
Angular also provides the inject() function for obtaining dependencies in supported injection contexts.
import { Component, inject } from '@angular/core';
import { CourseService } from './course.service';
@Component({
selector: 'app-course',
templateUrl: './course.component.html'
})
export class CourseComponent {
private courseService =
inject(CourseService);
courseName = '';
loadCourse(): void {
this.courseName =
this.courseService.getCourseName();
}
}
Important
The inject() function retrieves a dependency from Angular's dependency injection system without declaring it as a constructor parameter.
5. Constructor Injection vs inject()
| Constructor Injection | inject() |
|---|---|
| Dependency is declared as a constructor parameter. | Dependency is obtained using the inject() function. |
| Common and easy to understand. | Useful in supported Angular injection contexts. |
| Works naturally with class dependencies. | Can reduce constructor parameters. |
Example: constructor(private service: Service)
|
Example: private service = inject(Service)
|
6. Dependency and Provider
Angular needs to know how a dependency should be provided. This information is configured through providers or service metadata.
@Injectable({
providedIn: 'root'
})
export class TrainingService {
}
@Component({
selector: 'app-dashboard',
providers: [
TrainingService
],
templateUrl: './dashboard.component.html'
})
export class DashboardComponent {
}
Key Idea
The provider determines how Angular can resolve the requested dependency in the appropriate injector hierarchy.
7. How Angular Resolves a Dependency
When a component requests a dependency, Angular looks for a matching provider in its injector hierarchy.
Component
|
↓
Requests CourseService
|
↓
Current Injector
|
↓
Provider Found?
|
├── Yes → Create / Reuse Service
|
└── No → Look in Parent Injector
|
↓
Continue Hierarchy
Simple Idea
Angular follows its injector hierarchy to find a provider that can satisfy the dependency request.
8. Using an Injected Service in ngOnInit()
After a service has been injected, it can be used during component initialization to load or prepare data.
courses: string[] = [];
constructor(
private courseService: CourseService
) {
}
ngOnInit(): void {
this.courses =
this.courseService.getCourses();
}
The injected service provides the course data during component initialization.
9. Injecting a Service into Another Service
Angular services can also have dependencies on other services.
@Injectable({
providedIn: 'root'
})
export class NotificationService {
show(message: string): void {
console.log(message);
}
}
@Injectable({
providedIn: 'root'
})
export class TrainingService {
constructor(
private notificationService:
NotificationService
) {
}
saveCourse(): void {
this.notificationService.show(
'Course saved successfully'
);
}
}
Important
Dependency Injection is not limited to components. Services can also receive dependencies through Angular's injector.
10. Dependency Through an Abstraction
Angular can also use injection tokens when the dependency is represented by an abstraction rather than a concrete class.
export const API_URL =
new InjectionToken<string>('API_URL');
Why Use an Injection Token?
Injection tokens are useful when Angular needs to inject a value or dependency that cannot be represented directly by a class type.
Complete CIIT Training Institute Example
Suppose the CIIT Training Institute dashboard needs course information and notifications. Both services can be injected into the dashboard.
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 {
show(message: string): void {
console.log(message);
}
}
import {
Component,
OnInit
} from '@angular/core';
import { CourseService }
from './course.service';
import { NotificationService }
from './notification.service';
@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.show(
'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
Available Courses
- 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 another class |
CourseService
|
| Constructor Injection | Receive dependency through constructor |
constructor(...)
|
| inject() | Obtain dependency through Angular's inject function |
inject(Service)
|
| Provider | Defines how dependency is provided |
providedIn
|
| Injector | Resolves dependencies |
Injector
|
Important Points About Injecting Dependencies
- A dependency is an object required by another class.
- Angular can provide dependencies through its injector.
- Constructor injection is a common way to receive services.
- The inject() function can obtain dependencies in supported injection contexts.
- Providers tell Angular how dependencies should be supplied.
- Services can themselves have dependencies.
Dependency Injection Best Practices
- Prefer Angular's Dependency Injection system instead of manually creating service objects.
- Keep constructor dependencies meaningful and focused.
- Use services for reusable application logic.
- Choose an appropriate provider scope for each dependency.
- Avoid injecting unnecessary services into a component.
- Use injection tokens when a value or abstraction requires one.
Summary
Angular Dependency Injection allows a component or service to receive the objects it needs from Angular's injector.
Dependencies can be injected using constructor injection or inject(), while providers define how Angular resolves those dependencies.