Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 74 ยท Dependency Injection and Services

Providers, InjectionToken and Scopes

Learn Angular providers (useClass, useValue, useFactory, useExisting), InjectionToken, multi providers, component and route scopes and environment injectors, with a runnable mini DI.

Services and Dependency Injection used the simplest form: a class marked @Injectable({ providedIn: 'root' }), requested with inject(). Real applications need more. You want to inject a configuration string such as an API address, swap an implementation depending on the environment, collect many validators into one list, or give each component its own private copy of a service.

All of that is controlled by providers. A provider is a recipe that tells an injector how to produce the value for a token. This lesson covers the recipe types, the InjectionToken for things that are not classes, the places where providers can live (which determines scope), and how lookups travel through the injector tree. A runnable mini DI at the end lets you watch the rules play out.

Real versus stand-in. The typescript blocks are real Angular and read-only, because the site cannot run the Angular compiler. The runnable examples use a hand-written mini injector with tokens, provider recipes, multi and a parent chain. It models the rules; it is not Angular's code, and real Angular has more features such as self/host options and environment-injector APIs.

A provider is a token plus a recipe

When you write providers: [UserService], that is shorthand for the long form { provide: UserService, useClass: UserService }. The token (provide) is the key that code asks for. The recipe says how to get the value. There are four recipes.

TypeScript
providers: [
  // 1. useClass: create an instance of a class (often a different one than the token)
  { provide: LoggerService, useClass: ConsoleLoggerService },

  // 2. useValue: hand out a ready-made value (config, constants, fakes)
  { provide: API_URL, useValue: 'https://api.example.test' },

  // 3. useFactory: run a function, which may call inject() itself
  {
    provide: ApiClient,
    useFactory: () => new ApiClient(inject(API_URL), inject(LoggerService)),
  },

  // 4. useExisting: an alias, so both tokens return the SAME instance
  { provide: AuditLog, useExisting: LoggerService },
]

useClass is what lets you ask for an abstraction and receive a concrete class, for instance replacing a real PaymentGateway with a FakePaymentGateway in tests or development. useValue is for values that already exist. useFactory is for anything that needs logic to build; since Angular 14 the factory can use inject() instead of a separate deps array. useExisting does not create anything, it redirects, which is how one service can be reachable under two names without being duplicated.

InjectionToken: tokens that are not classes

A class works as a token because it exists at runtime. TypeScript interfaces and plain values do not: you cannot inject "a string" or "an interface". InjectionToken<T> creates a unique runtime key that carries a type.

TypeScript
import { InjectionToken } from '@angular/core';

export interface AppConfig {
  apiUrl: string;
  pageSize: number;
}

export const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');

// A token can describe its own default, so it needs no provider at all:
export const API_URL = new InjectionToken<string>('API_URL', {
  providedIn: 'root',
  factory: () => '/api',
});
TypeScript
// Provided once, where the app starts:
bootstrapApplication(AppComponent, {
  providers: [{ provide: APP_CONFIG, useValue: { apiUrl: '/api', pageSize: 20 } }],
});

// Used anywhere:
private readonly config = inject(APP_CONFIG);   // typed as AppConfig

The string passed to the constructor is only a label for error messages. Two tokens with the same label are still different keys. A neat pattern is a provideXyz() function that hides the token, so callers never see it; Angular's own provideRouter() and provideHttpClient() are built this way, and you can write your own with makeEnvironmentProviders().

Multi providers

Normally a second provider for the same token replaces the first. With multi: true, providers for a token accumulate, and injecting the token returns an array of all values. This is the extension-point mechanism: plugins register themselves, and the consumer receives them all.

TypeScript
export const VALIDATORS = new InjectionToken<((value: string) => string | null)[]>('VALIDATORS');

providers: [
  { provide: VALIDATORS, useValue: required, multi: true },
  { provide: VALIDATORS, useValue: maxLength(20), multi: true },
]

private readonly validators = inject(VALIDATORS);   // an array with both functions

All providers for one token must agree: either all are multi or none are. Many Angular features use this internally, such as route-level and global initializers.

Where you provide decides the scope

The same recipe behaves differently depending on which injector holds it, because each injector creates and caches its own instance.

  • Root (providedIn: 'root' or bootstrapApplication providers). One instance for the whole application. This is the right default.
  • Route providers. A route can declare providers: [AdminService], which creates an environment injector for that route and its children. The instance lives as long as that part of the route tree, and lazy-loaded routes get their own injector.
  • Component or directive providers. providers: [CartDraftService] in a @Component gives each component instance its own service instance, created with the component and destroyed with it. Children of that component, including projected content, can inject the same instance. There is also viewProviders, which hides the provider from content projected into the component.
TypeScript
@Component({
  selector: 'app-product-page',
  providers: [CartDraftService],            // one draft per page instance
  template: `...`,
})
export class ProductPageComponent {
  protected readonly draft = inject(CartDraftService);
}
flowchart TD
  R["Root environment injector<br/>Analytics, Theme"] --> A["ProductPage #1 injector<br/>CartDraft (own copy)"]
  R --> B["ProductPage #2 injector<br/>CartDraft (own copy)"]
  R --> L["Lazy route injector<br/>AdminService"]

A component-level provider creates one instance per component; root services stay shared.

A lookup starts at the requesting injector and walks up until a provider is found. A service is created in the injector that holds its provider, and its own dependencies are looked up from there. So a component-scoped CartDraftService can use the root Analytics, but a root service can never see something that is provided only in a component. inject() accepts options to adjust the search: { optional: true } returns null instead of throwing, { self: true } looks only in the current injector, { skipSelf: true } starts at the parent (useful to wrap or extend an ancestor's value), and { host: true } stops at the host component.

Recipes in a mini injector

This stand-in implements tokens, the four recipes and multi. Watch for the alias returning the identical instance, the factory using inject(), and the clear error for an unknown token.

TypeScript Provider recipes, InjectionToken and multi in a mini DI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Logger was requested but a ConsoleLogger came back, because the recipe was useClass. The audit token returns the very same object as Logger (alias), the factory built ApiClient from two other injectables, and the two CHECKS providers arrived together as an array. Unknown tokens fail loudly with the token's label, which is why you should always give an InjectionToken a meaningful description.

Scopes in a mini injector hierarchy

Now the hierarchy. Each "page" gets its own child injector holding a CartDraft, while Analytics lives in the root. A fourth injector overrides Theme but uses skipSelf to read the parent's value.

TypeScript Component-level providers and the injector chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The two pages hold different drafts but report to one shared Analytics, which is the effect of providing at component level versus root. Asking the root for CartDraft fails, because lookups only go up: parents never see what children provide. Finally, the darkPanel injector shadows Theme for itself and its descendants, while skipSelf reaches past the override to the parent's version.

@Injectable versus @Inject

Two decorators with similar names do different jobs, and mixing them up is a classic interview question.

@Injectable() goes on a class and says "this class can be created by the injector." Its options, mainly providedIn, say where it is registered. Services that receive dependencies through their constructor need it; with inject(), it is mostly there for providedIn.

@Inject(TOKEN) goes on a constructor parameter and says "give me whatever is registered for this token." You need it when the token is not the parameter's type: an InjectionToken, a string, or an abstract type that has no runtime value.

TypeScript
import { Inject, Injectable, InjectionToken, inject } from '@angular/core';

export const API_URL = new InjectionToken<string>('API_URL');

@Injectable({ providedIn: 'root' })
export class ApiClient {
  // Old style: the decorator tells Angular which token fills this parameter.
  constructor(@Inject(API_URL) private baseUrl: string) {}
}

@Injectable({ providedIn: 'root' })
export class ModernApiClient {
  // Current style: no parameter decorator, and the token is type-checked.
  private baseUrl = inject(API_URL);
}

In new code, inject(API_URL) replaces @Inject(API_URL). It is typed from the token, works in field initializers and needs no decorator. The other parameter decorators have function equivalents too: @Optional() is inject(X, { optional: true }), @Self() is { self: true }, @SkipSelf() is { skipSelf: true } and @Host() is { host: true }.

You may also read about the ReflectiveInjector, the injector of Angular 2 to 4 that resolved providers at run time. It was replaced by the StaticInjector in version 5 (which is why you register providers instead of relying on reflection) and removed in version 16. Today Injector.create({ providers }) is the way to build one by hand.

Choosing the scope

  • Start with root. State that the whole app shares (current user, cart, settings) belongs there.
  • Use a component provider when each instance of a widget needs its own state, such as a form draft, a wizard's step state or a table's sorting. It is created and cleaned up with the component.
  • Use route providers for services that only a feature area needs, so they are created only when the route is visited.
  • Use InjectionToken plus useValue or useFactory for configuration, feature flags and abstractions, and prefer provideSomething() helper functions for anything you ship to other apps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does { provide: Logger, useClass: ConsoleLogger } mean?

    The token is Logger, the recipe creates a ConsoleLogger. This is how an abstraction or a test double is swapped in.
  2. 2. Why do you need InjectionToken for a configuration object?

    InjectionToken gives a typed runtime key. The description string is only a label for error messages.
  3. 3. Three providers use the same token with multi true. What does inject(token) return?

    Multi providers accumulate. Without multi, a later provider simply replaces an earlier one.
  4. 4. A component declares providers [CartDraftService]. Two instances of the component are on the page. How many CartDraftService objects exist?

    Component providers create a new instance for every component instance. Root-provided services stay shared.
  5. 5. What does inject(X, { skipSelf: true }) do?

    skipSelf is useful when a component overrides a service but still needs the version provided by an ancestor.

Summary

  • A provider pairs a token with a recipe: useClass, useValue, useFactory or useExisting (an alias to the same instance).
  • InjectionToken<T> is the runtime key for values and interfaces; it can carry a default factory.
  • multi: true collects providers into an array, which suits plugin-style extension points.
  • Scope follows the injector that holds the provider: root for app-wide singletons, route injectors for feature areas, component providers for per-instance state.
  • Lookups walk up the tree and never down; optional, self, skipSelf and host adjust the search.

Next: State Management with Signals and Services.