angularangular-dependency-injection

Call service method to provide other services within app.module.ts


I have a configuration service that provides a method called getConfiguration(): Observable <Configuration>.

In order to fill my external library, I would like to provide this method within app.module.ts (I want to fill the InjectionToken, which is expected in the library).

Now I wonder how I can/should call this logic in the providers block.

@NgModule({
  declarations: [AppComponent],
  imports: [
      //...
  ],
  providers: [
    {
        provide: MY_CONFIG,
        useValue: ConfigurationService.getConfiguration(), // <--- won't work!
    }
  ]
  bootstrap: [AppComponent],
})
export class AppModule {}

Can you help me with that?


Solution

  • If your library expects the token to be Observable <Configuration>, then you can use factory to provide the Observable value as follows:

    More details on using factory provider: https://angular.io/guide/dependency-injection-providers#using-factory-providers

    
        function configFactory(configService: ConfigurationService) {
            return configService.getConfiguration();
        }
    
        ...
        providers: [
            {
                provide: MY_CONFIG,
                useFactory: configFactory,
                deps: [ConfigurationService]
            }
        ]
        ...