2

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?

reza
  • 5,972
  • 15
  • 84
  • 126
  • 1
    Yes. `injector.get()`. RTM, https://angular.io/docs/ts/latest/guide/dependency-injection.html – Estus Flask Feb 28 '17 at 22:21
  • thanks for the quick and accurate reply, i think I can use that scheme based on configuration parameter values. – reza Feb 28 '17 at 22:33

1 Answers1

1

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] }
  ],
  ...
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567