Issue
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).
Solution
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),
}
]
Answered By - MoxxiManagarm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.