Sub topic 5
Registering Providers
This chapter assumes you can write standalone components, bootstrap an app with bootstrapApplication, and create a service with @Injectable. It also assumes you have used inject() to request a dependency.
What a provider is
When a consumer calls inject(CartService), Angular needs answers to two questions. Which key is being requested? How should a value be produced for that key? A provider answers both. It pairs a token (the lookup key) with a recipe (the instructions for creating the value).
providedIn: 'root' is one way to register a provider: the service class registers itself. You can also register providers explicitly in several places, and that choice decides who can see the service and how many instances exist.
The shorthand and the long form
The most common provider is just a class in a providers array:
providers: [CartService]That line is shorthand for an object literal:
providers: [{ provide: CartService, useClass: CartService }]provide is the token, and useClass is the recipe. The long form matters because the token and the recipe do not have to match. The next chapter covers useClass, useValue, useFactory, and useExisting in detail. For now, keep in mind that every entry in a providers array reduces to this { provide, use... } shape.
Where you can register providers
| Location | Syntax | Scope |
|---|---|---|
| The service itself | `@Injectable({ providedIn: 'root' })` | Whole app, tree-shakable |
| Application bootstrap | `bootstrapApplication(App, { providers: [...] })` | Whole app |
| A route | `providers: [...]` on a `Route` | That route and its children |
| A component or directive | `providers: [...]` in `@Component` | That element and its subtree |
Application-level providers
Bootstrap providers are a good fit for services that cannot use providedIn. Examples include third-party classes you do not own and configuration values. This is also where Angular's provide* functions go:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
import { AnalyticsService } from './app/analytics.service';
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(),
provideRouter(routes),
AnalyticsService
]
});A function like provideHttpClient() returns a bundle of providers. Libraries hide their internal tokens behind functions like this so that you only need one call.
Route-level providers
A route can carry its own providers. Angular creates an environment injector for that route, and the route's components and child routes can see those providers. Combined with lazy loading, the service code is only downloaded when someone visits the route.
import { Routes } from '@angular/router';
import { AdminService } from './admin/admin.service';
export const routes: Routes = [
{
path: 'admin',
providers: [AdminService],
loadComponent: () =>
import('./admin/admin.component').then(m => m.AdminComponent)
}
];Component-level providers create one instance per component. A later chapter covers them in detail.
Common errors
- Duplicate registration. If a class has
providedIn: 'root'and you also list it in a component'sproviders, that component gets a separate instance. State does not flow between the two copies, which often looks like a bug where "updates don't show up." - Providing an interface. TypeScript interfaces do not exist at runtime, so they cannot be tokens. Use an abstract class or an
InjectionTokeninstead. - Missing
@Injectable. A class that injects its own dependencies needs@Injectable()when it is listed inproviders, even withoutprovidedIn.
Exercise
A team lists ReportService (which has providedIn: 'root') in the providers array of the /reports route. Components inside /reports and the app's header component both inject it. How many instances exist, and why?
Show answer
Two instances exist. The header resolves ReportService from the root environment injector. The route's own environment injector also has a provider for it, so components under /reports find that one first and get a separate instance. To share a single instance, remove the route-level registration.
Exercise
Rewrite providers: [Logger] in long form.
Show answer
providers: [{ provide: Logger, useClass: Logger }]