🅰️ Angular Q33 / 125

What is providedIn: root in Angular services?

AI-Powered Answer ✓ Answered

In Angular, the providedIn: 'root' property is a crucial mechanism for configuring how services are provided and made available throughout your application, ensuring efficiency and proper dependency injection.

What is providedIn: 'root'?

When you set providedIn: 'root' in the @Injectable() decorator of an Angular service, you are telling Angular to provide this service at the root level of the application's dependency injection system. This makes the service available as a singleton instance across the entire application.

This modern approach, introduced in Angular 6+, simplifies service provision compared to the older method of adding services to the providers array of an NgModule, such as AppModule.

Key Benefits

  • Automatic Tree-Shaking: Services provided in 'root' are automatically tree-shaken by the Angular CLI. If a service is never injected anywhere in your application, it won't be included in the production build, leading to smaller bundle sizes.
  • Singleton Instance: Guarantees a single, application-wide instance of the service. Every component or service that injects it will receive the exact same instance.
  • Simplified Dependency Injection: Eliminates the need to manually add services to the providers array of AppModule or any other module, making services easier to manage and provide.
  • Lazy Loading Compatibility: Works seamlessly with lazy-loaded modules, as the root injector is always available.

How It Works

When an Angular application starts, the root injector (often referred to as the 'platform injector' or 'application-wide injector') is created. Services marked with providedIn: 'root' are registered with this root injector.

Any component, directive, or other service within the application that requests this service via dependency injection will receive the single instance managed by the root injector. Angular will create this instance only when it's first requested.

Example

typescript
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // This makes MyService a singleton available throughout the app
})
export class MyService {
  private counter = 0;

  constructor() {
    console.log('MyService instance created');
  }

  increment() {
    this.counter++;
  }

  getCounter() {
    return this.counter;
  }
}

When to Use It

Use providedIn: 'root' for services that are truly application-wide and should be singletons. This includes services for authentication, global state management, logging, shared utility functions, or data services that fetch and manage application-level data.

Alternatives

While 'root' is common, services can also be provided in a specific feature module (e.g., providedIn: SomeFeatureModule) or directly in a component's providers array (providers: [MyService]) if you need a separate instance per component or within a specific module context.