Reputation: 6358
I have a requirement, based on configuration parameters, pick a specific service as an injectable to the component. All the examples I see, really use a specific service and use it at component construction time.
Is there a way to perform this injection at run time?
Upvotes: 2
Views: 1010
Reputation: 657228
You can use a factory that returns a different instance depending on some configuration
@NgModule({
providers: [
ConfigService,
{ provide: APP_BASE_HREF, useFactory: loadConfig, deps: [ConfigService] },
],
...
see also How to pass parameters rendered from backend to angular2 bootstrap method
function myServiceFactory(config:ConfigService) {
switch(config.someProp) {
case 'someValue': return new ClassA();
default: return new ClassB();
}
}
@Component({
providers: [
{ provide: MyService, useFactory: myServiceFactory, deps: [ConfigService] }
],
...
Upvotes: 1