I have a MessageService in my application shared in various modules and used by a component which display thoses messages. By default, I ask people who use it to provide it in the component, so they don't have to enter a key to select the messages they want to display in the list. If they want to do so a simple boolean on the service tell the algorithm to filter the messages with the key or not.
By default this boolean named "isProvidedInComponent" is true since I believe that people do not need the following feature : use case of component A the source of message adding message(s) to component B, the displayer.
I want to know if there is a way in Angular to automatically set this boolean according to the way the service instance of the service is provided:
- True if the service is provided in component (so we return all the messages of the list since they are proper to the component)
- False if the service is provided in a module (so I need my algorithm to filter the messages on a key given, and throw an error if messages do not have one).
CodePudding user response:
Add the flag to your constructor
@Injectable()
class MessageService {
constructor(private myFlag: boolean) {}
}
And set the flag with a factory
In module it will look like
providers:[
{
provide: MessageService,
useFactory: () => new MessageService(false),
}
]
While in component it will be
providers:[
{
provide: MessageService,
useFactory: () => new MessageService(true),
}
]
CodePudding user response:
The only way to change the "providing" of a service is through a module :
providers:[
{
provide: MessageService,
useFactory: () => ..., // useValue, useClass, useExisting
}
]
If you wish to setup your service according to a component, you will have to make a factory/facade, which you could call like so :
service: MessageService = this.base
.withFilter('some filter')
.withCondition(true);
// ... And so on
constructor(private base: MessageService) {}