Sub topic 5
Registering Providers
This chapter assumes you know TypeScript classes and generics, standalone components, and bootstrapApplication. It also assumes you have read the earlier chapters on @Injectable and on injecting with inject(). Here you will learn what a provider is, every place you can register one, and how that choice affects instance count, bundle size, and the errors you see.
What a provider actually is
When you call inject(CartService), Angular does not look for the class itself. It looks for a provider, which is an instruction with two parts:
- A token: the key the consumer asks for. Usually the token is a class, but it can also be an
InjectionToken. - A recipe: how to produce the value for that token, for example "construct this class" or "return this object".
Registering a provider means putting that instruction into an injector. An injector stores providers and caches the instances it creates. If no injector the consumer can reach has a provider for the token, Angular throws an error. It never constructs a class just because the class exists.
The shortest provider form is the class on its own:
providers: [AnalyticsService]Angular expands this to the full object form:
providers: [{ provide: AnalyticsService, useClass: AnalyticsService }]The next chapter covers the object form's recipes (useClass, useValue, useFactory, useExisting). This chapter is about where the provider goes.
The places you can register a provider
| Registration site | Injector that holds it | Instances | Tree-shakable |
|---|---|---|---|
| `@Injectable({ providedIn: 'root' })` | Root environment injector | One per application | Yes |
| `bootstrapApplication(..., { providers })` | Root environment injector | One per application | No |
| Route `providers` | A child environment injector for that route | One per route config | No, but lazy chunks keep it out of the main bundle |
| Component `providers` / `viewProviders` | That component's element injector | One per component instance | No |
| `@Injectable({ providedIn: 'platform' })` | Platform injector | One per page, shared across apps | Yes |
providedIn: 'root'
You already used this form in the @Injectable chapter:
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartService {
private readonly items = signal<string[]>([]);
readonly count = computed(() => this.items().length);
add(item: string): void {
this.items.update(list => [...list, item]);
}
}In this form the provider lives on the class, not in an array. The build tool keeps CartService in the bundle only if some code actually injects it. This is why providedIn: 'root' is the default choice for application-wide services.
bootstrapApplication providers
The second argument to bootstrapApplication is an ApplicationConfig. Its providers array goes into the same root environment injector:
import { Injectable } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
@Injectable()
export class AnalyticsService {
track(event: string): void {
console.log('track', event);
}
}
bootstrapApplication(AppComponent, {
providers: [
provideRouter(routes),
provideHttpClient(),
AnalyticsService
]
}).catch(err => console.error(err));AnalyticsService has @Injectable() with no providedIn. That means it has no provider of its own, so it has to be listed somewhere. Because it is referenced directly in this array, it stays in the main bundle even if nothing injects it.
Use this site for things you configure at startup: library setup functions like provideRouter and provideHttpClient, configuration values, and classes that need a non-default recipe.
Route providers
A route can carry its own providers. When the router activates that route for the first time, it creates a child environment injector that holds them. Every component rendered under that route, including child routes, can inject those services.
import { Injectable } from '@angular/core';
import { Routes } from '@angular/router';
@Injectable()
export class AdminAuditService {
readonly entries: string[] = [];
record(action: string): void {
this.entries.push(`${new Date().toISOString()} ${action}`);
}
}
export const routes: Routes = [
{
path: 'admin',
providers: [AdminAuditService],
loadChildren: () =>
import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
},
{ path: '', loadComponent: () =>
import('./home/home.component').then(m => m.HomeComponent) }
];AdminAuditService is available in the admin section only. If HomeComponent tries to inject it, Angular throws an error, because the home route's injector chain never passes through the admin route's injector.
Two details matter here:
- The route injector is created once and kept. Navigating away from
/adminand back does not create a newAdminAuditService. Do not treat route providers as "reset per visit" state. - If the route is lazily loaded and the service file is imported only from the lazy chunk, the service stays out of the main bundle.
Component providers
A component's providers array registers services in that component's element injector. Each instance of the component gets its own service instance. viewProviders is a variant that hides the service from projected content. The chapter on scoping services to a component subtree covers both. For now, remember that this is the only site that gives you one instance per component.
providedIn: 'platform' and 'any'
providedIn: 'platform' places the service in the platform injector, above the root. It matters only when several Angular applications run on the same page and need to share one instance. providedIn: 'any' (one instance per lazily loaded environment injector) is deprecated. Avoid both unless you have a specific reason.
Packaging providers with makeEnvironmentProviders
Angular libraries expose setup functions such as provideRouter(). You can follow the same convention for your own features:
import {
EnvironmentProviders,
Injectable,
makeEnvironmentProviders
} from '@angular/core';
@Injectable()
export class FeatureFlagService {
private readonly flags = new Set<string>();
enable(flag: string): void { this.flags.add(flag); }
isOn(flag: string): boolean { return this.flags.has(flag); }
}
export function provideFeatureFlags(): EnvironmentProviders {
return makeEnvironmentProviders([FeatureFlagService]);
}Callers then write providers: [provideFeatureFlags()] in bootstrapApplication or on a route. The EnvironmentProviders return type is a type-level guard: if someone puts provideFeatureFlags() in a component's providers array, the compiler rejects it. This stops setup that should exist once from being repeated in every component instance.
Common errors and how to read them
NullInjectorError: No provider for X
This is the error you will see most often. It looks roughly like this:
NullInjectorError: R3InjectorError(Standalone[AppComponent])[AnalyticsService -> AnalyticsService]:
NullInjectorError: No provider for AnalyticsService!The bracketed chain shows the path of tokens Angular was resolving. "Null injector" is the empty injector at the very top of the hierarchy. Reaching it means every injector on the path was checked and none had a provider. Typical causes:
- The class has
@Injectable()withoutprovidedIn, and nobody listed it in anyprovidersarray. - The provider is registered on a route or component that is not an ancestor of the consumer.
- The provider is registered in a lazily loaded part of the app, and an eagerly loaded consumer injects it.
The fix is to add providedIn: 'root' or to register the provider at a site that is an ancestor of every consumer.
Accidental duplicate instances
A service with providedIn: 'root' can also be listed in a component's providers. Angular allows it, and the result is two instances: the root one and one per component. This is a common source of "my state is not updating" bugs, where one component writes to its local copy and another reads the root copy.
import { Component, inject } from '@angular/core';
import { CartService } from './cart.service';
@Component({
selector: 'app-mini-cart',
standalone: true,
providers: [CartService], // creates a private CartService for this component
template: `Mini cart: {{ cart.count() }}`
})
export class MiniCartComponent {
protected readonly cart = inject(CartService);
}MiniCartComponent will always show 0 here, even after other components call add() on the root cart. Remove the providers entry to share the root instance.
Missing @Injectable on a class with dependencies
If a class calls inject() in field initializers, it still works when Angular constructs it through a provider. If it uses constructor parameters instead, it needs @Injectable() so the compiler records what to pass in. Without the decorator, Angular cannot resolve constructor parameters and throws at creation time. Keep @Injectable() on every service, even ones with no dependencies today.
Choosing a registration site
Use this order of preference:
providedIn: 'root'for a single shared instance with the default recipe. This covers most services.bootstrapApplicationproviders for library setup, configuration values, and app-wide providers that need a non-default recipe.- Route providers when a service belongs to one feature area and should be invisible outside it.
- Component providers when each component instance needs its own copy.
Exercise
A service is declared with @Injectable() (no providedIn) and registered in the providers of the /reports route. A HeaderComponent rendered by AppComponent, outside the router outlet, injects it. What happens, and what are two ways to fix it?
Show answer
Angular throws NullInjectorError. HeaderComponent's injector chain goes up to the root environment injector and never passes through the /reports route injector. Fix it by adding providedIn: 'root' to the service, or by moving the provider into bootstrapApplication's providers, so it sits in an injector that is an ancestor of HeaderComponent.
Exercise
You navigate to /admin, record three audit entries in AdminAuditService (registered in the admin route's providers), go to the home page, then return to /admin. How many entries does the service hold, and why?
Show answer
Three. The router creates the route's environment injector the first time the route activates and keeps it afterward, so returning to /admin reuses the same AdminAuditService instance.
Exercise
Why does provideFeatureFlags() return EnvironmentProviders instead of a plain Provider array?
Show answer
EnvironmentProviders can only be placed in environment injectors (bootstrapApplication or route providers). The type makes the compiler reject it in a component's providers array, which prevents creating a separate set of feature-flag services for every component instance.