liveBook · Manning

DI token

As explained in Modern Angular

A DI token is an Angular identifier used by the dependency-injection system to locate a provider and obtain a dependency.

A DI token is an Angular identifier that tells the dependency-injection system what dependency to locate and return. Providers map tokens to concrete values, while injection requests the value associated with a token. section 2.3.2 section 3.1.2

A class such as AuthService can serve as a token when requested through a constructor parameter. Angular resolves it from a provider declared in a component or NgModule, or from a service marked providedIn: 'root'. section 2.3.2

Modern standalone applications move provider configuration into ApplicationConfig. Existing standalone APIs such as provideHttpClient() can register dependencies directly, while importProvidersFrom() brings providers from older modules into the application configuration. section 1.3.3 section 2.3.2

A minimal token-and-injector mechanism

A small Injector can register a dependency under an InjectionToken and later retrieve it. An HttpClient is provided as httpToken; UserService injects that token and uses the resulting client to request users. section 3.1.2

Listing 3.1 Injector class for a naive implementation of a DI mechanism
class InjectionToken<T> {  #1
  constructor(public value: T) {}
}

class Injector {
  private readonly dependencies = new Map<
    InjectionToken<any>, any
  >();  #2

  provide<T>(dependency: T): InjectionToken<T> {  #3
    const token = new InjectionToken(dependency);
    this.dependencies.set(token, dependency);
    return token;
  }

  inject<T>(token: InjectionToken<T>): T {  #4
    const dependency = this.dependencies.get(token) as T;
    return dependency;
  }
}

Review the compact InjectionToken and Injector listing to see token registration, storage, and lookup in executable form. section 3.1.2

How Modern Angular covers it

How deep it goes
Explains registration and lookup with a primitive Injector, then stops short of Angular's deeper implementation details.
Examples
Uses AuthService, HttpClient, UserService, InjectionToken, Injector, ApplicationConfig, and provideHttpClient() as concrete examples.
What it assumes
Assumes familiarity with Angular services and constructor injection while briefly reviewing providers and injection from first principles.
What you can do after
Understand how to register dependencies under tokens and retrieve them through Angular's legacy or standalone provider patterns.
How it connects
Connects DI tokens with dependency injection, providers, injectors, InjectionToken, NgModules, and standalone APIs.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.