Blog>
Snippets

Injection Token for Angular Configurations

Illustrate how to inject configuration settings into an Angular service using an InjectionToken.
import { InjectionToken } from '@angular/core';

// Define the configuration interface
export interface AppConfig {
  apiEndpoint: string;
  title: string;
}

// Create an InjectionToken with the interface as its type
export const APP_CONFIG = new InjectionToken<AppConfig>('app.config');
Defines an AppConfig interface and creates an InjectionToken for that interface to be used in Angular's dependency injection system.
import { NgModule } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app-config';

// Define the actual configuration value to provide
const APP_DI_CONFIG: AppConfig = {
  apiEndpoint: 'https://api.example.com',
  title: 'My Angular App'
};

@NgModule({
  providers: [
    { provide: APP_CONFIG, useValue: APP_DI_CONFIG }
  ]
})
export class AppConfigModule {}
Creates an Angular module that provides the actual configuration object for the APP_CONFIG InjectionToken.
import { Injectable, Inject } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app-config';

@Injectable({
  providedIn: 'root'
})
export class ExampleService {
  constructor(@Inject(APP_CONFIG) private config: AppConfig) {
    console.log('API endpoint:', config.apiEndpoint);
  }

  getTitle(): string {
    return this.config.title;
  }
}
Example of an Angular service that injects the configuration using the APP_CONFIG InjectionToken and reveals a method to get the title from the configuration.