reza
reza

Reputation: 6358

How to pick an Angular 2 service for a component at runtime

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

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

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

Related Questions