Register Angular providers dynamically during runtime

274 views Asked by At

Is there a way to register module/component providers in a dynamic way? I know about the useFactory option but this is only about a specific provider. What I want to achieve is to register some providers during runtime, via a service instance.

Take the following code for example, where the BarService instance has a property that contains multiple providers, this service is provided in module level and then a contained component provides all these services in order to be accessible in the DI.

@Injectable()
export class BarService {
  public readonly manyProviders: Provider[] = [Service1, Service2, Service3];
}

@NgModule({
  providers: [BarService],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html',
   providers: [...barServiceInstance.manyProviders]
})
export class FooComponent {
  public constructor(private service1: Service1) {
   ...
  }
}

I've tried to use the useFactory approach, but the services are not resolved (which makes sense I guess...):

export function barServiceProviderFactory(barServiceInstance: BarService) {
  return barServiceInstance.manyProviders;
}

@NgModule({
  providers: [BarService, {provide: 'barServiceProviders', useFactory: barServiceProviderFactory, deps: [BarService] }],
  ...
})

@Component({
   selector: 'foo-component',
   templateUrl: './foo.component.html'
})
export class FooComponent {
  public constructor(@Inject('barServiceProviders') private services: any[]) {
   // services array contains the types and not the instantiated/resolved services.
  }
}
0

There are 0 answers