0 day streak
javascript / intermediate
Snippet

Polymorphic Service Substitution with Abstract Classes and Providers

Using an abstract class as a Dependency Injection token enables subtype polymorphism in Angular. Components depend on the abstract contract, while providers supply concrete derived implementations at runtime without breaking component code.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Injectable, Provider } from '@angular/core';
export abstract class NotificationProvider {
abstract sendAlert(message: string): void;
}
@Injectable()
export class PushNotificationProvider extends NotificationProvider {
sendAlert(message: string): void {
console.log(`Push Alert: ${message}`);
}
}
export const NOTIFICATION_CONFIG: Provider = {
provide: NotificationProvider,
useClass: PushNotificationProvider
};
angular
Breakdown
1
export abstract class NotificationProvider {
Declares an abstract token class that defines the public contract without supplying concrete behavior.
2
export class PushNotificationProvider extends NotificationProvider {
Extends the base class and provides a concrete implementation of the abstract method.
3
provide: NotificationProvider, useClass: PushNotificationProvider
Maps the abstract base type token to the concrete child class in the dependency injection container.