javascript / intermediate
Snippet
Abstract Class Polymorphism via Angular InjectionToken Providers
TypeScript abstract classes define polymorphic contracts without emitting overhead. By coupling an abstract base class with an Angular InjectionToken and default factory, consumers can inject the abstract interface directly, allowing runtime implementations to be swapped across modules or testing suites.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Injectable, InjectionToken } from '@angular/core';export abstract class BaseNotifier {abstract sendAlert(message: string): void;}@Injectable()export class ToastNotifier extends BaseNotifier {sendAlert(message: string): void {console.warn(`[TOAST]: ${message}`);}}export const NOTIFIER_TOKEN = new InjectionToken<BaseNotifier>('NOTIFIER_TOKEN', {providedIn: 'root',factory: () => new ToastNotifier()});
angular
Breakdown
1
export abstract class BaseNotifier { abstract sendAlert(message: string): void; }
Declares the abstract class establishing the required method signatures for derived classes.
2
export const NOTIFIER_TOKEN = new InjectionToken<BaseNotifier>('NOTIFIER_TOKEN', {
Creates a strongly typed injection token with a root-level default implementation.