0
0
AngularConceptBeginner · 3 min read

What is Injection Token in Angular: Simple Explanation and Example

In Angular, an InjectionToken is a unique key used to provide and inject values or objects that don't have a class type. It helps Angular's dependency injection system identify and deliver these values safely and clearly.
⚙️

How It Works

Imagine you have a toolbox with many tools, but some tools don't have a clear label or shape. Angular's dependency injection needs a clear label to find and give you the right tool. An InjectionToken acts like a unique label or name tag for these tools (values or objects) that don't have a class or type.

When you create an InjectionToken, you give Angular a special key to store and retrieve a value. Later, when a component or service asks for that key, Angular knows exactly what to give back. This avoids confusion and errors, especially when injecting simple values like strings or configuration objects.

💻

Example

This example shows how to create an InjectionToken for a configuration object and inject it into a service.

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

// Create an InjectionToken for app config
export const APP_CONFIG = new InjectionToken<{apiUrl: string}>('app.config');

// Provide the config value
export const appConfigValue = { apiUrl: 'https://api.example.com' };

@Injectable({ providedIn: 'root' })
export class ApiService {
  private config = inject(APP_CONFIG);

  getApiUrl(): string {
    return this.config.apiUrl;
  }
}

// In your module providers array:
// providers: [
//   { provide: APP_CONFIG, useValue: appConfigValue }
// ]
Output
ApiService.getApiUrl() returns 'https://api.example.com'
🎯

When to Use

Use InjectionToken when you want to inject values that are not classes, such as strings, objects, or functions. It is especially useful for configuration settings, constants, or feature flags that your app needs in many places.

For example, if you want to provide an API URL or a theme setting across your app, InjectionToken lets you do this cleanly and safely without confusing Angular's injector.

Key Points

  • InjectionToken creates a unique key for dependency injection.
  • It is used for injecting non-class values like strings or objects.
  • Helps Angular avoid conflicts when injecting simple values.
  • Commonly used for app-wide configuration or constants.

Key Takeaways

InjectionToken provides a unique key for injecting non-class values in Angular.
Use InjectionToken to safely inject configuration objects or constants.
It helps Angular's dependency injection system avoid confusion with simple values.
InjectionToken is essential for clean and maintainable app-wide settings.