Angular 使用服务的其他方式
我希望在组件的构造函数之后加载适当的服务 我知道在组件中使用服务的方法是在构造函数中调用它。但我希望能够根据组件中的数据加载这个或那个服务。 以便以后能够调用相应的服务 会话的一个组成部分的粗略示例Angular 使用服务的其他方式,angular,typescript,service,Angular,Typescript,Service,我希望在组件的构造函数之后加载适当的服务 我知道在组件中使用服务的方法是在构造函数中调用它。但我希望能够根据组件中的数据加载这个或那个服务。 以便以后能够调用相应的服务 会话的一个组成部分的粗略示例 _currentSendingService; // a service constructor(private _alert : AlertService) { this.foo(); } foo() { if (condition) { this._current
_currentSendingService; // a service
constructor(private _alert : AlertService)
{
this.foo();
}
foo() {
if (condition) {
this._currentSendingService = SmsService // not working idea of what i want
}
else {
this._currentSendingService = EmailService
}
}
sendMessage() {
this._currentSendingService.send(message)
}
一种方法是将所有服务放在构造函数中并实例化一个var
constructor(private _alert : AlertService, private _smsService:SmsService, private _emailService:EmailService)
{
this.foo();
}
在foo()中执行此操作
但是如果我使用了很多服务,它会这样做吗?(想象一下,如果我有大约20个可用的服务,但根据场景的不同,只使用其中的一个)通过这种方式触发每个服务的构造函数,这可能是我不想要的行为
示例:我们加载一个组件,根据其数据,我们希望使用SmsService作为_currentSendingService,因为我们在对话中的消息类型仅在SMS中。
所以当我使用_currentSendingService.send(“消息”);它将使用SmsService.send(“消息”)方法。
如果你能告诉我怎么做,我就找不到了。我找到的所有关于服务的文档都告诉我在构造函数中注册它。
感谢您花时间阅读我的问题您可以使用Factory模式表单GOF设计模式来创建和维护界面
export interface IMessage{
send();
}
然后在您的SMS服务
和电子邮件服务
export class SMSService implements
{
send(){
//your implementation
}
}
对于电子邮件服务也应该这样做,然后创建messageservicefactory
export class MessageServiceFactory{
getInstance(yourcondition):IMessage{
if(condition){
return new SMSService();
}else{
return EmailSerivce();
}//you can also use switch case here
}
然后将messageserivcefactory注入到组件中,并使用
_messageService:IMessage;
constructor(private _messageServiceFactory :MessageServiceFactory)
{
_messageService=__messageServiceFactory.getInstance(condition);
}
sendMessage() {
this._messageService.send(message)
}
与其注入所有可能的服务,不如注入一个服务工厂,负责解决您的类所需的特定服务。@ChrisPickford谢谢,这正是我想要的,我来看看它是如何工作的。我会编辑我的帖子,如果我能让它工作的话,我会做一个回答。谢谢你的回答,这是最好的方式,我会努力实现它。我以前从未使用过接口。是时候开始了。如果我得到一个问题,我会回来:)我让它工作,正是我想要的谢谢。我还有一个问题。如果我的服务EmailService在其构造函数中有类似(private http:Httpclient)的内容,我必须在MessageService构造函数和getInstance()中实现它;我必须返回EmailSerivce(this.http);这就是我所做的(它正在工作),但有更好的方法吗?是的,你可以用这种方法来做,另一种方法是不创建
新的
对象,只需将这些服务注入消息服务,你可以根据需要决定
_messageService:IMessage;
constructor(private _messageServiceFactory :MessageServiceFactory)
{
_messageService=__messageServiceFactory.getInstance(condition);
}
sendMessage() {
this._messageService.send(message)
}