Angular InjectionToken
Angular InjectionToken is used to create a unique token that can represent a value, configuration object, interface, or other dependency that cannot be identified directly by a class.
What is InjectionToken?
Angular dependency injection normally uses a class type to identify a dependency. However, some dependencies are values or abstractions that do not have a runtime class representation.
InjectionToken provides a unique token that Angular can use to identify and inject such dependencies.
Simple Definition
An InjectionToken is a unique key used by Angular's Dependency Injection system to identify a value or non-class dependency.
InjectionToken Flow
Why Use InjectionToken?
Unique Identifier
Provides a unique identifier for a dependency.
new InjectionToken()
Configuration
Useful for injecting application configuration values.
API_URL
Non-Class Values
Can represent strings, objects, arrays, and other values.
string | object
Abstraction
Can represent dependencies that are not concrete classes.
Token
1. Basic InjectionToken Syntax
An InjectionToken can be created by importing InjectionToken from Angular core.
import { InjectionToken } from '@angular/core';
export const API_URL =
new InjectionToken<string>('API_URL');
Important
The generic type <string> describes the type of value associated with the token.
2. Providing a Value with InjectionToken
After creating a token, a provider can associate a value with it.
import { ApplicationConfig } from '@angular/core';
import { API_URL } from './tokens';
export const appConfig: ApplicationConfig = {
providers: [
{
provide: API_URL,
useValue: 'https://api.example.com'
}
]
};
3. Injecting an InjectionToken
Once a value is registered against a token, it can be injected into a component.
import {
Component,
Inject
} from '@angular/core';
import { API_URL } from './tokens';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent {
constructor(
@Inject(API_URL)
private apiUrl: string
) {
}
}
How it works
Angular uses the API_URL token to locate the value registered by the provider and supplies that value to the component.
4. Injecting a Token with inject()
An InjectionToken can also be obtained using Angular's inject() function.
import {
Component,
inject
} from '@angular/core';
import { API_URL } from './tokens';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent {
private apiUrl =
inject(API_URL);
}
5. InjectionToken for String Values
A token can represent a simple string configuration value.
export const APP_NAME =
new InjectionToken<string>('APP_NAME');
{
provide: APP_NAME,
useValue: 'CIIT Training Institute'
}
6. InjectionToken for Configuration Objects
InjectionToken can also represent an object containing multiple configuration values.
export interface AppConfig {
apiUrl: string;
environment: string;
enableLogging: boolean;
}
export const APP_CONFIG =
new InjectionToken<AppConfig>('APP_CONFIG');
{
provide: APP_CONFIG,
useValue: {
apiUrl: 'https://api.example.com',
environment: 'production',
enableLogging: true
}
}
Benefit
A single token can represent a structured configuration object instead of creating separate dependencies for every setting.
7. InjectionToken with Factory Provider
A factory provider can calculate or create the value associated with an InjectionToken.
export const CURRENT_ENVIRONMENT =
new InjectionToken<string>('CURRENT_ENVIRONMENT');
{
provide: CURRENT_ENVIRONMENT,
useFactory: () => {
return 'production';
}
}
How it works
Instead of directly providing a fixed value, Angular calls the factory function to obtain the dependency value.
8. Optional Token Dependency
A dependency can be marked optional when the application should continue working even if no provider is found for that dependency.
import {
Component,
inject
} from '@angular/core';
import {
APP_CONFIG
} from './app-config';
@Component({
selector: 'app-config',
templateUrl: './config.component.html'
})
export class ConfigComponent {
config = inject(
APP_CONFIG,
{ optional: true }
);
}
Use Case
Optional dependencies can be useful when a configuration or feature is not guaranteed to have a provider.
9. InjectionToken vs Service
| InjectionToken | Service |
|---|---|
| Represents a value, configuration, or abstraction. | Usually represents a class containing functionality. |
| Useful for non-class dependencies. | Useful for reusable application logic. |
| Example: API URL or application configuration. | Example: CourseService or TrainingService. |
| Uses a unique token as the DI key. | The class itself can act as the DI token. |
10. Common InjectionToken Use Cases
API URL
Store a backend API endpoint as injectable configuration.
API_URL
App Name
Provide application-specific string configuration.
APP_NAME
Configuration
Provide structured application settings.
APP_CONFIG
Feature Flag
Provide feature configuration through dependency injection.
ENABLE_FEATURE
11. How Angular Resolves an InjectionToken
Component
|
↓
Requests API_URL
|
↓
Angular Injector
|
↓
Searches Provider
|
↓
API_URL Provider Found
|
↓
Returns Registered Value
|
↓
Component Receives Value
Complete CIIT Training Institute Example
Suppose the CIIT Training Institute Angular application needs a configurable API URL and institute name. InjectionToken can be used to provide these values through Angular Dependency Injection.
import { InjectionToken }
from '@angular/core';
export const API_URL =
new InjectionToken<string>('API_URL');
export const INSTITUTE_NAME =
new InjectionToken<string>('INSTITUTE_NAME');
export const appConfig: ApplicationConfig = {
providers: [
{
provide: API_URL,
useValue:
'https://api.example.com'
},
{
provide: INSTITUTE_NAME,
useValue:
'CIIT Training Institute'
}
]
};
import {
Component,
inject
} from '@angular/core';
import {
API_URL,
INSTITUTE_NAME
} from './tokens';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html'
})
export class DashboardComponent {
apiUrl = inject(API_URL);
instituteName =
inject(INSTITUTE_NAME);
}
<h2>
{{ instituteName }}
</h2>
<p>
API URL:
{{ apiUrl }}
</p>
CIIT Training Institute
API URL: https://api.example.com
InjectionToken Quick Reference
| Concept | Purpose | Example |
|---|---|---|
| InjectionToken | Creates a unique DI identifier |
new InjectionToken<string>()
|
| provide | Associates a provider with the token |
provide: API_URL
|
| useValue | Provides a fixed value |
useValue: 'API'
|
| useFactory | Creates the dependency using a factory |
useFactory
|
| inject() | Retrieves the token value |
inject(API_URL)
|
Important Points About InjectionToken
- InjectionToken creates a unique identifier for a dependency.
- It is useful for values and dependencies that do not have a class type at runtime.
- Tokens can represent strings, objects, configuration, and other values.
- Providers associate values or factories with the token.
- Components can retrieve token values through Dependency Injection.
- InjectionToken is especially useful for configurable application settings.
InjectionToken Best Practices
- Use clear and descriptive token names.
- Keep configuration tokens grouped in a meaningful file.
- Use appropriate generic types for token values.
- Avoid creating duplicate tokens for the same dependency.
- Keep provider configuration easy to understand and maintain.
- Use InjectionToken when a dependency cannot be represented naturally by a class.
Summary
Angular InjectionToken provides a unique identifier that can be used by the Dependency Injection system for values, configuration objects, and other non-class dependencies.
A token is associated with a provider using options such as useValue or useFactory, and the resulting dependency can then be injected into components or services.