Angular course · Module 5: Services and DI

Injector Hierarchy

1 min read ·
In this lesson4

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

Injector Levels

Root Injector (Shogun)
    ↓
Module Injectors (Daimyo)
    ↓
Element Injectors (Castles)
    ↓
Component Injectors (Halls)

providedIn Options

// 1. Root - Singleton for the entire application
@Injectable({ providedIn: 'root' })
export class GlobalService { }

// 2. Any - New instance for each lazy-loaded module (deprecated since Angular 15, do not use in new code)
@Injectable({ providedIn: 'any' })
export class ScopedService { }

// 3. Platform - Shared between multiple Angular applications
@Injectable({ providedIn: 'platform' })
export class SharedService { }

Providers in a Component

@Component({
  selector: 'app-dojo',
  standalone: true,
  providers: [
    TrainingService  // New instance for each component instance
  ],
  template: `...`
})
export class DojoComponent {
  private training = inject(TrainingService);
}

Providers vs providedIn: 'root'

FeatureprovidedIn: 'root'providers: []
InstanceSingletonPer component/module
Tree-shakingYesNo
Lazy loadingOptimalNeeds import
UsageMost servicesPer-instance services

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. 1. What does 'providedIn: root' mean in the @Injectable decorator?

  2. 2. What happens when we add a service to 'providers' in the @Component decorator?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Order the injector levels from highest to lowest:

  • Click in order

    Build the entry that registers a service at the component level (one line):

  • Code editor

    Complete the component with its own CounterService instance in providers.

Useful articles