0
0
AngularConceptBeginner · 3 min read

What is providedIn root in Angular: Explanation and Example

providedIn: 'root' in Angular means a service is registered with the root injector, making it a singleton available throughout the app. This ensures Angular creates one shared instance of the service automatically without needing to add it to any module's providers.
⚙️

How It Works

Think of providedIn: 'root' as telling Angular, "Please create one shared service instance for the whole app." This is like having a single coffee machine in an office that everyone uses instead of each room having its own. Angular's root injector acts like the office manager who keeps track of this one coffee machine.

When you add providedIn: 'root' to a service, Angular automatically registers it at the highest level. So, whenever any part of your app asks for that service, Angular gives the same instance. This saves memory and keeps data consistent across your app.

💻

Example

This example shows a simple Angular service with providedIn: 'root'. It will be created once and shared everywhere.

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

@Injectable({
  providedIn: 'root'
})
export class LoggerService {
  log(message: string) {
    console.log('LoggerService:', message);
  }
}

// Usage in a component
import { Component } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({
  selector: 'app-root',
  template: `<button (click)="logMessage()">Log Message</button>`
})
export class AppComponent {
  constructor(private logger: LoggerService) {}

  logMessage() {
    this.logger.log('Button clicked!');
  }
}
Output
LoggerService: Button clicked!
🎯

When to Use

Use providedIn: 'root' when you want a service to be a singleton shared across your entire Angular app. This is common for services that manage data, logging, user authentication, or configuration.

It simplifies your code by removing the need to add the service to any module's providers array. Angular handles the service creation and sharing automatically.

Key Points

  • Singleton: One instance shared app-wide.
  • Automatic registration: No need to add to module providers.
  • Root injector: The highest-level injector in Angular.
  • Memory efficient: Avoids multiple instances.
  • Recommended: For most app-wide services.

Key Takeaways

providedIn: 'root' makes a service a singleton available throughout the Angular app.
It registers the service with Angular's root injector automatically.
Use it for services that should be shared and reused across components.
It removes the need to manually add the service to module providers.
This pattern improves app performance and code simplicity.