We use cookies to enhance your experience on the site
CodeWorlds

Dependency Injection - The Castle Supply System

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)

1import { Component, inject } from '@angular/core';
2import { KatanaService } from './services/katana.service';
3
4@Component({
5  selector: 'app-forge',
6  standalone: true,
7  template: \`
8    <h2>Katana Forge</h2>
9    <button (click)="forgeKatana()">🔥 Forge a Katana</button>
10    <ul>
11      @for (katana of katanas; track katana.id) {
12        <li>{{ katana.name }} - {{ katana.damage }} DMG</li>
13      }
14    </ul>
15  \`
16})
17export class ForgeComponent {
18  private katanaService = inject(KatanaService);
19  katanas = this.katanaService.getAll();
20
21  forgeKatana(): void {
22    this.katanaService.forge('Masamune', 'Tachi');
23    this.katanas = this.katanaService.getAll();
24  }
25}

Method 2: Constructor Injection (classic)

1@Component({...})
2export class ForgeComponent {
3  constructor(private katanaService: KatanaService) {}
4
5  forgeKatana(): void {
6    this.katanaService.forge('Masamune', 'Tachi');
7  }
8}

inject() vs Constructor

| Feature | inject() | Constructor | |---------|----------|-------------| | Syntax | Simpler | Standard | | Use in functions | Yes (with limitations) | No | | Inheritance | Easier | Requires super() | | Testing | Similar | Similar |

Go to CodeWorlds