← Back to Angular, page 2

angular-0022 · Medium mid

How do you configure providers in Angular DI: useClass, useValue, useFactory, useExisting, InjectionToken and multi providers?

A provider tells an injector how to create the value for a token. useClass builds an instance of a class, useValue returns a fixed value, useFactory runs a function (which can call inject()), and useExisting makes one token an alias of another. An InjectionToken names non-class values, and multi: true collects several values under one token.

Full answer

Every DI lookup uses a token. For a class the token is the class itself. The provider says what to give for that token.

  • { provide: Logger, useClass: ConsoleLogger } builds a ConsoleLogger whenever Logger is requested. This allows swapping the implementation, for example in a test. An abstract class makes a good token and type at the same time.
  • { provide: APP_CONFIG, useValue: { apiUrl: '/api' } } supplies a ready-made object or constant.
  • { provide: ApiClient, useFactory: () => new ApiClient(inject(APP_CONFIG)) } runs a function. Inside it you can call inject(), so the value can depend on other services or on the environment.
  • { provide: OldLogger, useExisting: Logger } makes two tokens return the same instance.
  • multi: true lets several providers add to a list under one token, such as validators or interceptors. The injected value is an array.

Interfaces and plain objects do not exist at runtime, so they cannot be tokens. Use new InjectionToken<AppConfig>('APP_CONFIG'). A token can carry a default: new InjectionToken('X', { factory: () => ... }), and with providedIn: 'root' the token is tree-shakable and needs no registration.

Where providers are placed decides how many instances exist. ApplicationConfig.providers and providedIn: 'root' give one per app. A route's providers gives one per lazy route tree. A component's providers gives one per component instance.

The example creates a plain injector, so it runs under Node without a browser.

typescript
import { InjectionToken, Injector, inject } from '@angular/core';

interface AppConfig {
  apiUrl: string;
  retries: number;
}

type Validator = (value: string) => boolean;

const APP_CONFIG = new InjectionToken<AppConfig>('APP_CONFIG');
const VALIDATORS = new InjectionToken<Validator[]>('VALIDATORS');

abstract class Logger {
  abstract log(message: string): void;
}

class ConsoleLogger extends Logger {
  log(message: string): void {
    console.log('[console]', message);
  }
}

class ApiClient {
  private readonly config = inject(APP_CONFIG);
  private readonly logger = inject(Logger);

  describe(): void {
    this.logger.log(`API ${this.config.apiUrl} with ${this.config.retries} retries`);
  }
}

const injector = Injector.create({
  providers: [
    { provide: APP_CONFIG, useValue: { apiUrl: 'https://api.example.test', retries: 3 } },
    { provide: Logger, useClass: ConsoleLogger, deps: [] },
    { provide: ApiClient, useFactory: () => new ApiClient(), deps: [] },
    { provide: VALIDATORS, useValue: (v: string) => v.length > 0, multi: true },
    { provide: VALIDATORS, useValue: (v: string) => !v.includes(' '), multi: true },
  ],
});

injector.get(ApiClient).describe();
injector.get(Logger).log('same logger instance everywhere');

const checks = injector.get(VALIDATORS);
console.log('validators', checks.length, 'ok', checks.every((check) => check('has space')));

Tested on Angular 20.3 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`). It uses `Injector.create`, so no browser is needed. Output: the API line, the logger lines, and `validators 2 ok false`.

Key points

  • Provider forms: `useClass`, `useValue`, `useFactory`, `useExisting`, plus `multi`.
  • Use `InjectionToken` for configuration and other non-class values.
  • Factories can call `inject()`, which lets them depend on other tokens.
  • Provider location decides the lifetime and number of instances.

Common mistakes

  • Using an interface as a token. It is erased at compile time.
  • Forgetting `multi: true` and having the last provider silently replace the others.
  • Putting configuration in a global variable instead of a token, which makes tests harder.

Follow-ups

  • What is the difference between `useClass` and `useExisting`?
  • How would you override a root service in one lazy route only?
  • Why make a token tree-shakable?

Tips

  • Walk through one example per provider type in a single sentence each.
  • Explain why interfaces cannot be tokens. It is a very common trap.
  • Mention overriding providers in tests as the main practical benefit.

Evaluation rubric

  • Names and explains all provider forms.
  • Knows InjectionToken and multi.
  • Understands provider scope.