javascript - Angular dynamicky injektovat službu
Používám Angular 11. Vytvářím stránku s formulářem se třemi poli.
- Text zprávy: Vstupní text
- Uživatel: Vstupní text
- Způsob odeslání: Vyberte (Email, SMS, Telegram)
<select>
<option value="EmailService">Email</option>
<option value="SmsService">SMS</option>
<option value="TelegramService">Telegram</option>
</select>
A tlačítko Odeslat zprávu (zavolat metodu sendMessageClick)
Chci zavolat funkci sendmessage na službách na základě vybrané možnosti SendMethod.
Mé služby:
// 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
}
}
A moje logika komponenty:
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");
}
}
Ale nemohu to rozjet.
Jak to mohu získat?
A jak mohu vytvořit obecnou funkční komponentu, aby nebylo potřeba přidávat budoucí nové služby do anotace poskytovatele?