Sub topic 6
Application-wide singletons with providedIn root
This chapter assumes you can write a standalone component, you have used a service through inject(), and you know that Angular builds a tree of injectors. Earlier chapters covered providers and tokens, inject(), and the split between environment and element injectors. Here the focus is the most common provider registration in Angular: providedIn: 'root'.
What providedIn root does
A class marked @Injectable({ providedIn: 'root' }) is registered in the root environment injector. That injector belongs to the application, so every component, directive, pipe, and service in the app gets the same instance.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly count = signal(0);
increment(): void {
this.count.update(n => n + 1);
}
}You don't list the service in any providers array. Any code that calls inject(CounterService) reaches the root environment injector eventually and finds the registration there.
Two components that inject this service share its state:
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter-display',
standalone: true,
template: `<p>Count: {{ counter.count() }}</p>`,
})
export class CounterDisplayComponent {
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-counter-button',
standalone: true,
template: `<button (click)="counter.increment()">Add</button>`,
})
export class CounterButtonComponent {
protected readonly counter = inject(CounterService);
}Clicking the button in one component updates the display in the other, because both hold a reference to the same object.
Lazy creation
Angular does not create root services when the application starts. It creates one the first time something asks for it, and then caches it in the root injector. Every later request returns the cached object.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class LoggerService {
constructor() {
console.log('LoggerService created');
}
log(message: string): void {
console.log(message);
}
}If no code ever injects LoggerService, the constructor never runs and the message never prints. If you need startup work, such as registering listeners, you must request the service explicitly, for example from an app initializer or the root component. Don't rely on the service being present just because it is registered.
Tree-shaking
The registration lives on the service class itself. This is what makes it tree-shakable. If nothing in your code references LoggerService, the bundler can drop the class from the build.
Compare this with listing a service in the providers array of bootstrapApplication. That array references the class directly, so the class stays in the bundle even if no one injects it. For services that every build should contain regardless of usage, that is acceptable. For most services, providedIn: 'root' gives smaller bundles with no extra effort.
Where the root injector sits
When a component calls inject(), Angular first searches the element injectors, moving up the component tree. Then it moves to the environment injectors: any route-level environment injector, then the root, then the platform. The root environment injector is the last stop before the platform in most applications, so a root service is found only if nothing closer provides the same token.
Overriding a root default
providedIn: 'root' also works on an InjectionToken that has a default factory. This gives you a configuration value that works with no setup but can be replaced when the application boots.
import { InjectionToken } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
export const API_URL = new InjectionToken<string>('API_URL', {
providedIn: 'root',
factory: () => '/api',
});
bootstrapApplication(AppComponent, {
providers: [{ provide: API_URL, useValue: 'https://example.com/api' }],
});Both registrations target the root environment injector. The explicit provider passed to bootstrapApplication takes precedence over the token's default factory. Code that injects API_URL receives 'https://example.com/api'. If you remove the providers entry, it receives '/api'.
Comparing registration options
| Registration | Scope | Tree-shakable | Instances |
|---|---|---|---|
| `providedIn: 'root'` | Whole application | Yes | One per application |
| `providers` in `bootstrapApplication` | Whole application | No | One per application |
| `providers` on a route | Components under that route | No | One per route environment injector |
| `providers` on a component | That component and its descendants | No | One per component instance |
The first two rows end up in the same injector. They differ in bundling, and in who owns the decision: the service author for providedIn, the application author for bootstrapApplication.
Edge cases
Closer providers shadow the root
The root registration is only the fallback. If a component lists CounterService in its own providers, injections inside that component and its descendants get a separate instance from the element injector, and the root one is never consulted. The same applies to a route that lists the service in providers. The service class is identical in each case. Only the injector that satisfies the request changes.
Lazy-loaded routes still share the root service
Lazy-loaded routes get their own environment injector, but its parent is the root. A providedIn: 'root' service injected inside a lazy route resolves to the same single instance. You get a second instance only if something in the lazy part registers the service again, for example in a route's providers or in the providers of a lazy-loaded NgModule.
Server-side rendering creates one root per request
On the server, each incoming request bootstraps its own application, so each request has its own root injector and its own copy of every root service. State in a root service is therefore not shared between users. Module-level variables, by contrast, live for the whole server process and are shared. Keep per-user data in services, never in module-level variables.
Tests get a fresh root
TestBed builds a new root injector for each test, so root services start clean every time.
import { TestBed } from '@angular/core/testing';
import { CounterService } from './counter.service';
it('starts from zero in every test', () => {
TestBed.configureTestingModule({});
const counter = TestBed.inject(CounterService);
expect(counter.count()).toBe(0);
counter.increment();
expect(counter.count()).toBe(1);
});To replace a root service, add a provider for it in configureTestingModule({ providers: [...] }). That provider goes into the test's root injector and wins over the providedIn default, in the same way the bootstrapApplication provider did above.
Platform scope
providedIn: 'platform' registers the service in the platform injector instead. The platform injector is shared by every Angular application bootstrapped on the same page. This matters only for micro-frontend setups that run several applications side by side. For a normal single application, 'root' is the right choice.
Pitfalls
When choosing where to register a service, ask who should own the state. If the whole application needs one copy, use providedIn: 'root'. If each component instance or each route needs its own copy, use a narrower scope, which later chapters cover.
Exercise
A service is marked @Injectable({ providedIn: 'root' }). A component lists the same service in its providers array. A child of that component injects the service. Which instance does the child get, and why?
Show answer
The child gets the instance created by the parent component's element injector. Angular checks element injectors first, moving up the component tree, and finds the provider on the parent before it reaches the root environment injector. The root instance is not used for that subtree.
Exercise
You change a providedIn: 'root' service to be listed in the providers array of bootstrapApplication instead, and you remove the providedIn option. The application behaves the same, but the bundle gets larger for builds where no code injects the service. Why?
Show answer
A class named in a providers array is referenced from application code, so the bundler cannot tell it is unused and keeps it. With providedIn: 'root', the registration lives on the class, so if nothing references the class, the bundler can remove it entirely.