Angular Inject service dynamically

Viewed 624

I'm using Angular 11. I'm creating a form page with 3 fields.

  • MessageText: Input Text
  • ToUser: Input Text
  • SendMethod: Select (Email, Sms, Telegram)
<select>
   <option value="EmailService">Email</option>
   <option value="SmsService">SMS</option>
   <option value="TelegramService">Telegram</option>
</select>

And a button Send Message (call sendMessageClick method)

I want to call a sendmessage function on Services based on SendMethod option selected.

My services:

// Inteface
export abstract class IMessagingService {
  abstract sendMessage(text: string, address: string): bool;
}

// Email Service
import {Injectable} from '@angular/core';
import {IMessagingService} from './IMessagingService';

@Injectable({
  providedIn: 'root'
})
export class EmailService implements IMessagingService {

  constructor() { }

  sendMessage(text: string, address: string): bool {
    /* logic here*/
    return true
  }
}

// Sms Service
import {Injectable} from '@angular/core';
import {IMessagingService} from './IMessagingService';

@Injectable({
  providedIn: 'root'
})
export class SmsService implements IMessagingService {

  constructor() { }

  sendMessage(text: string, address: string): bool {
    /* logic here*/
    return true
  }
}

// Telegram Service
import {Injectable} from '@angular/core';
import {IMessagingService} from './IMessagingService';

@Injectable({
  providedIn: 'root'
})
export class TelegramService implements IMessagingService {

  constructor() { }

  sendMessage(text: string, address: string): bool {
    /* logic here*/
    return true
  }
}

And my component logic:

import {Component, Injector} from '@angular/core';
import {IMessagingService} from '../service/IMessagingService';
import {EmailService} from '../service/email.service';
import {SmsService} from '../service/sms.service';
import {TelegramService} from '../service/telegram.service';

@Component({
  selector: 'app-send-message-user',
  templateUrl: './send-message-user.component.html',
  styleUrls: ['./send-message-user.component.scss'],
  providers: [EmailService, SmsService, TelegramService]
})
export class SendMessageUserComponent {

  constructor(private scriptInjector: Injector, private script: IMessagingService) {
  }

  sendMessageClick(serviceSelected: string): void {
    this.script = this.scriptInjector.get(serviceSelected);
    let returnStatus = this.script.sendMessage("Message", "User adress");
  }
}

But I cannot make this work.

How can I get this?

And how can I make a generic working component to not needed to add future new services on provider annotation?

0 Answers
Related