Angular Dependency Injection In Depth- Injection Tokens

Centralized Configuration in Angular using Injection Tokens

In Angular applications, it’s common to have configuration settings that need to be accessed throughout the app. These settings can include things like API URLs, feature flags, or any other application-specific parameters. To maintain flexibility and easy customization of these settings, we can utilize Injection Tokens in Angular.

Introduction to Injection Tokens

Injection Tokens provide a way to define and identify dependencies in Angular. They allow for more flexibility in resolving dependencies and can be used in scenarios where multiple instances of a dependency need to be managed or where configuration settings need to be shared across the app.

Scenario: Application Configuration

In our Todo Management app, we have various configuration settings that are crucial for its proper functioning. These settings include the API URL and whether logging is enabled or not. We want to make these configuration settings available throughout our application and allow for easy customization.

Implementation Steps
Let’s walk through the steps of implementing centralized configuration using Injection Tokens:

Step 1: Define the Injection Token

First, we need to define an Injection Token to represent our application configuration. This will allow us to map the configuration settings in a standardized way. Here’s an example:

import { InjectionToken } from '@angular/core';

export interface AppConfig {
  apiUrl: string;
  enableLogging: boolean;
}
export const APP_CONFIG = new InjectionToken<AppConfig>('AppConfig');

In the code snippet above, we define an interface AppConfig that represents our application configuration settings. We also create an Injection Token APP_CONFIG to map these settings.

Step 2: Create the Configuration Service

Next, we create a configuration service that provides the configuration settings to other parts of the application. This service will be responsible for injecting the configuration via the Injection Token. Here’s an example implementation:

import { Injectable, Inject } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app-config';

@Injectable({ providedIn: 'root' })
export class ConfigService {
  constructor(@Inject(APP_CONFIG) private config: AppConfig) {}

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

  get enableLogging(): boolean {
    return this.config.enableLogging;
  }
}

In the code snippet above, we create a ConfigService and use the @Inject decorator to inject the value associated with the Injection Token APP_CONFIG into the config parameter of the constructor. This allows us to access the configuration settings in other methods of the service.

Step 3: Provide the Configuration Settings

To make the configuration settings available throughout the application, we need to provide them using the Injection Token in our Angular module. Here’s an example:

import { NgModule } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app-config';
import { ConfigService } from './config.service';

const appConfig: AppConfig = {
  apiUrl: 'https://api.example.com',
  enableLogging: true
};

@NgModule({
  providers: [
    { provide: APP_CONFIG, useValue: appConfig },
    ConfigService
  ]
})
export class AppModule {
  
}

In the code snippet above, we provide the configuration settings using the APP_CONFIG Injection Token in the providers array of our Angular module. We use the useValue property to specify the actual configuration object.

Step 4: Use the Configuration in Components or Services

Once the configuration settings are provided, we can easily inject the ConfigService into any component or service and access the configuration values. Here’s an example usage in a component:

import { Component } from '@angular/core';
import { ConfigService } from './config.service';

@Component({
  selector: 'app-config',
  template: `
    <p>API URL: {{ apiUrl }}</p>
    <p>Logging Enabled: {{ enableLogging }}</p>
  `
})
export class ConfigComponent {
  constructor(private configService: ConfigService) {}

  get apiUrl(): string {
    return this.configService.apiUrl;
  }

  get enableLogging(): boolean {
    return this.configService.enableLogging;
  }
}

In the code snippet above, we inject the ConfigService into the ExampleComponent and use it to access the configuration settings. We can then use these settings in the template or any other component logic as needed.

Conclusion

Using Injection Tokens in Angular allows us to create a centralized configuration service that provides configuration settings throughout the application. This approach enables easy customization and flexibility in managing different configuration options.

By following the steps outlined in this blog post, you can effectively implement centralized configuration in your Angular applications using Injection Tokens. This ensures that your application’s configuration settings are easily accessible, customizable, and maintainable.

Demo

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم