Angular course Β· Module 5: Services and DI
Dependency Injection - The Castle Supply System
In this lesson2
Dependency Injection (DI) is a pattern where Angular automatically delivers dependencies to components and services - like a supply system delivering weapons and provisions to castles.
Injecting Services
Method 1: inject() (Angular 14+, recommended)
import { Component, inject } from '@angular/core';
import { KatanaService } from './services/katana.service';
@Component({
selector: 'app-forge',
standalone: true,
template: `
<h2>Katana Forge</h2>
<button (click)="forgeKatana()">Forge a Katana</button>
<ul>
@for (katana of katanas; track katana.id) {
<li>{{ katana.name }} - {{ katana.damage }} DMG</li>
}
</ul>
`
})
export class ForgeComponent {
private katanaService = inject(KatanaService);
katanas = this.katanaService.getAll();
forgeKatana(): void {
this.katanaService.forge('Masamune', 'Tachi');
this.katanas = this.katanaService.getAll();
}
}Method 2: Constructor Injection (classic)
@Component({...})
export class ForgeComponent {
constructor(private katanaService: KatanaService) {}
forgeKatana(): void {
this.katanaService.forge('Masamune', 'Tachi');
}
}inject() vs Constructor
| Feature | inject() | Constructor |
|---|---|---|
| Syntax | Simpler | Standard |
| Use in functions | Yes (with limitations) | No |
| Inheritance | Easier | Requires super() |
| Testing | Similar | Similar |
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. Which method of injecting services is recommended since Angular 14+?
2. What is Dependency Injection (DI) in Angular?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Horizontal ordering
Arrange the line that injects a service via inject() (left to right):
- Code editor
Complete the component so that it gets SamuraiService without a constructor, right in the field declaration.
- Vertical ordering
Order the lines of a component that injects a service via the constructor (the classic way):