Sub topic 2
Application-wide singletons with `providedIn: 'root'`
Assume you know TypeScript classes, standalone components, services, and basic route configuration. Angular dependency injection uses injectors, which are objects that create and return dependencies.
Application-wide singletons with `providedIn: 'root'`
A service declared with providedIn: 'root' belongs to the application's root environment injector. Angular creates one instance when the application first requests the service. All components that resolve the service from that injector receive the same instance.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly count = signal(0);
increment(): void {
this.count.update(value => value + 1);
}
}This is the usual choice for application-wide state, logging, or configuration. The provider is tree-shakable: Angular can omit it from a build when the application never uses it.
Scoping services to a route
A route can define providers for an environment injector created for that route:
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [AdminSettingsService],
},
];Components and services under /admin share one AdminSettingsService instance. Components outside that route cannot use that route-scoped instance. Leaving the route destroys its injector and its scoped services.
Element injectors follow the component tree
Angular also creates element injectors for component and directive instances. These injectors follow the rendered component tree.
When a component requests a service, Angular searches its element injector and then ancestor element injectors. If it finds no provider there, Angular continues through the relevant environment injectors.
One service instance per component with `providers`
Putting a service in a component's providers array creates a provider in that component's element injector. Each component instance then receives its own service instance.
@Component({
selector: 'app-counter',
standalone: true,
providers: [CounterService],
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterComponent {
protected readonly counter = inject(CounterService);
}Two <app-counter> elements have separate counters, even though CounterService also has providedIn: 'root'. The nearer component provider wins over the root provider.
Exercise
Two sibling components both inject a root-provided service. Do they receive the same instance?
Show answer
Yes. Unless one component or an ancestor provides a nearer replacement, both resolve the shared root instance.