Blog>
Snippets

Injection Token with useClass Provider

Show how to use an InjectionToken with the useClass provider to substitute a service implementation in Angular.
import { Injectable, InjectionToken, NgModule } from '@angular/core';
Import the necessary decorators and InjectionToken from Angular's core library.
export interface Logger { log(message: string): void; }
Define an interface for the Logger service to enforce a log method.
export const LOGGER_TOKEN = new InjectionToken<Logger>('Logger');
Create an InjectionToken to uniquely identify the Logger service within Angular's dependency injection system.
@Injectable()
class DefaultLoggerService implements Logger {
    log(message: string): void {
        console.log('Default Logger:', message);
    }
}
Create the default logger service that implements the Logger interface.
@Injectable()
class AlternateLoggerService implements Logger {
    log(message: string): void {
        console.warn('Alternate Logger:', message);
    }
}
Create an alternate logger service that also implements the Logger interface.
@NgModule({
    providers: [{ provide: LOGGER_TOKEN, useClass: AlternateLoggerService }]
})
class AppModule {}
Create an NgModule that provides the LOGGER_TOKEN with the useClass provider pointing to the AlternateLoggerService, overriding the default logger implementation.
import { Inject, Component } from '@angular/core';

@Component({
    selector: 'app-root',
    template: '<p>Check the console for log messages</p>'
})
class AppComponent {
    constructor(@Inject(LOGGER_TOKEN) private logger: Logger) {}

    ngOnInit() {
        this.logger.log('Application initialized.');
    }
}
Define a component that injects the Logger service using the LOGGER_TOKEN, allowing the AlternateLoggerService to be injected in place of the DefaultLoggerService.