Member-only story
Angular Dynamic Service Instantiation Using Injector
Dynamic service instantiation can be a powerful technique for creating flexible and scalable solutions in modern Angular applications. One use case is selecting a specific implementation of a service at runtime based on user input or application state. This post will explore how to achieve this using Angular’s Injector and provide a practical example of dynamically initializing payment services.
The Problem
Imagine an application that supports multiple payment methods, such as PayPal, Stripe, and Venmo. Each payment method has its own implementation but adheres to a common interface. Based on the user’s selection, the appropriate service needs to be instantiated dynamically at runtime. Angular’s Injector provides a seamless way to accomplish this.
Example Setup
Below is a sample implementation of dynamic service instantiation:
Service Definitions
First, define a base class PaymentBaseService and create specific services for each payment method.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class PaymentBaseService {
pay() {}
}
@Injectable({ providedIn: 'root' })
export class PaypalService extends PaymentBaseService {
constructor() {
super();
console.log('PaypalService!');
}
override pay() {
console.log('Paypal payment!');
}
}
@Injectable({ providedIn: 'root' })
export class…