We use cookies to enhance your experience on the site
CodeWorlds

Injector Hierarchy

Angular has a hierarchical injector structure - like a supply system from the Shogun through Daimyo to individual castles.

Injector Levels

1Root Injector (Shogun)
23Module Injectors (Daimyo)
45Element Injectors (Castles)
67Component Injectors (Halls)

providedIn Options

1// 1. Root - Singleton for the entire application
2@Injectable({ providedIn: 'root' })
3export class GlobalService { }
4
5// 2. Any - New instance for each lazy-loaded module
6@Injectable({ providedIn: 'any' })
7export class ScopedService { }
8
9// 3. Platform - Shared between multiple Angular applications
10@Injectable({ providedIn: 'platform' })
11export class SharedService { }

Providers in a Component

1@Component({
2  selector: 'app-dojo',
3  standalone: true,
4  providers: [
5    TrainingService  // New instance for each component instance
6  ],
7  template: \`...\`
8})
9export class DojoComponent {
10  private training = inject(TrainingService);
11}

Providers vs providedIn: 'root'

| Feature | providedIn: 'root' | providers: [] | |---------|-------------------|---------------| | Instance | Singleton | Per component/module | | Tree-shaking | Yes | No | | Lazy loading | Optimal | Needs import | | Usage | Most services | Per-instance services |

Go to CodeWorlds