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?

2
  • 1
    Yes. injector.get(). RTM, angular.io/docs/ts/latest/guide/dependency-injection.html Commented Feb 28, 2017 at 22:21
  • thanks for the quick and accurate reply, i think I can use that scheme based on configuration parameter values. Commented Feb 28, 2017 at 22:33

1 Answer 1

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] }
  ],
  ...
Sign up to request clarification or add additional context in comments.

2 Comments

where is MyService and ConfigService are defined? Part of angularCore?
No, that's just example names of custom classes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.