0
0
Angularframework~5 mins

Service scope (root, module, component) in Angular

Choose your learning style9 modes available
Introduction

Services in Angular help share data and logic. Service scope decides where the service lives and who can use it.

You want one shared service for the whole app.
You want a service only for a specific feature module.
You want a service unique to a single component and its children.
You want to control memory by limiting service lifetime.
You want different instances of a service in different parts of the app.
Syntax
Angular
@Injectable({ providedIn: 'root' })
@Injectable({ providedIn: SomeModule })
@Injectable({ providedIn: SomeComponent })

providedIn: 'root' means the service is a singleton for the whole app.

You can also provide services in modules or components to limit their scope.

Examples
This service is available everywhere in the app as a single instance.
Angular
@Injectable({ providedIn: 'root' })
export class UserService { }
This service is only available inside the AdminModule and its components.
Angular
@Injectable({ providedIn: AdminModule })
export class AdminService { }
This service instance is created only for SomeComponent and its child components.
Angular
@Injectable({ providedIn: SomeComponent })
export class LocalService { }
Sample Program

This example shows a service provided at root and another provided in a feature module. The FeatureComponent uses both services. The root service is shared app-wide, while the feature service is limited to the feature module.

Angular
import { Component, Injectable, NgModule } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class RootService {
  value = 'root';
}

@Injectable()
export class FeatureService {
  value = 'feature';
}

@Component({
  selector: 'app-feature',
  template: `Feature: {{ featureService.value }} | Root: {{ rootService.value }}`
})
export class FeatureComponent {
  constructor(public featureService: FeatureService, public rootService: RootService) {}
}

@NgModule({
  declarations: [FeatureComponent],
  providers: [FeatureService],
  exports: [FeatureComponent]
})
export class FeatureModule {}

@Component({
  selector: 'app-root',
  template: `<app-feature></app-feature> Root: {{ rootService.value }}`
})
export class AppComponent {
  constructor(public rootService: RootService) {}
}
OutputSuccess
Important Notes

Services provided in 'root' are singletons and live as long as the app runs.

Providing a service in a module or component creates a new instance limited to that scope.

Use component scope to isolate service instances for specific UI parts.

Summary

Service scope controls where and how long a service instance lives.

Use 'root' for app-wide singletons, modules for feature-specific services, and components for isolated instances.

Choosing the right scope helps manage memory and service sharing effectively.