Providers and injection tokens

Intermediate · 19 min

The four ways to tell an injector what to hand over, and InjectionToken for the things that aren't classes.

Before thisDependency injection fundamentals and the injector tree

Sunny Sood · 19 min

Providers and injection tokens

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Sunny SoodReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A provider is a recipe telling the injector how to produce a value for a given token — `useClass`, `useValue`, `useFactory`, and `useExisting` are four different recipes for the same job.
  • `InjectionToken` exists because a plain TypeScript interface or a primitive value (a string, a config object) has no class identity for the injector to key off of at runtime.
  • `useExisting` lets two different tokens resolve to the literal same instance — useful for aliasing without constructing a second object.

A provider is a recipe, not the value itself

The previous lesson’s constructor(private http: HttpClient) asked for an HttpClient without specifying how to build one — that’s the injector’s job. A provider is exactly that specification: a recipe telling the injector, “when something asks for this token, here’s how to produce a value for it.” Angular gives you four different recipes, each suited to a different situation.

The four provider shapes

providers: [
  { provide: Logger, useClass: ConsoleLogger },
  { provide: API_URL, useValue: 'https://api.example.com' },
  { provide: Logger, useFactory: () => new Logger(isDevMode()) },
  { provide: PrimaryLogger, useExisting: Logger },
]
  • useClass — “when asked for Logger, construct a ConsoleLogger instead.” This is how you swap an implementation without touching any code that depends on the original token — a test can provide useClass: MockLogger in place of the real one, and every consumer asking for Logger gets the mock, unaware anything changed.
  • useValue — “when asked for this token, hand back this exact value, already constructed.” No new call happens at all; you’re providing a literal value — a config object, a constant, a pre-built instance.
  • useFactory — “run this function to decide what to hand back.” This is the recipe for anything conditional: pick a different implementation based on an environment flag, construct something using values pulled from other injected dependencies, anything that needs actual logic rather than a fixed class or value.
  • useExisting — “when asked for this token, resolve it to the exact same instance as this other token.” Not a new object — a genuine alias, so two different injection tokens end up pointing at one shared instance rather than two separate ones.

InjectionToken: a key for things that aren’t classes

Every example so far used a class (Logger, ConsoleLogger) as the token being provided and requested — and a class works as a token because it survives compilation as a real, runtime-identifiable value. A plain interface doesn’t:

interface AppConfig {
  apiUrl: string;
}
// constructor(private config: AppConfig) {} — doesn't work; AppConfig
// is erased at compile time, leaving nothing for the injector to match on.

TypeScript interfaces exist only at compile time; by the time your code runs, AppConfig has vanished entirely. The injector needs something concrete to use as a lookup key, and an erased interface can’t be that. InjectionToken creates exactly that concrete, runtime-real key, for an interface or a primitive value with no class of its own to stand in for it:

const APP_CONFIG = new InjectionToken<AppConfig>('app.config');

providers: [{ provide: APP_CONFIG, useValue: { apiUrl: 'https://api.example.com' } }];

constructor(@Inject(APP_CONFIG) private config: AppConfig) {}
// or: private config = inject(APP_CONFIG);

The token itself (APP_CONFIG) is the thing with runtime identity; the type parameter (<AppConfig>) is purely for TypeScript’s benefit, giving you type safety on what you get back without needing a class to carry that type through to runtime.

Multi-providers: several values behind one token

Occasionally you want several providers to contribute to the same token rather than one replacing another — a plugin-style list of validators, say, where each feature module adds its own without needing to know about the others. That’s what the multi: true flag on a provider is for, and it’s exactly what this lesson’s linked “deeper” video walks through: injecting an array of providers registered against one shared token, rather than the single-value providers covered above.

This lesson’s main video runs through all four provider shapes with worked examples — watch for useFactory especially, since it’s the one that most often gets reached for before useClass would have been the simpler, equally correct choice.

Check yourself

  1. 01Why can't you write `constructor(private config: AppConfig)` if `AppConfig` is a plain TypeScript interface, not a class?

    Interfaces are erased at compile time — there's no `AppConfig` left at runtime for the injector to match against. A class survives compilation as a real, identifiable constructor function the injector can use as a lookup key; an interface leaves nothing behind. That's exactly the gap `InjectionToken` fills.

  2. 02What does `{ provide: Logger, useFactory: () => new Logger(isDevMode()) }` do that `{ provide: Logger, useClass: Logger }` can't?

    It lets you run arbitrary logic to decide *how* to construct the value — here, choosing different `Logger` behavior based on `isDevMode()` — rather than just pointing at a class and letting the injector call `new` on it with no further decision-making involved.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark