0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
EchtFettigerKeks
  • 1,692
  • 1
  • 18
  • 33
  • As far as I'm aware the only DI token that supports an asynchronous _provider_ is https://angular.io/api/core/APP_INITIALIZER (because the actual app doesn't start until it's resolved). Why not provide the configuration synchronously, but have it expose the config asynchronously? – jonrsharpe Dec 13 '21 at 14:54

1 Answers1

1

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]
        }
    ]
    ...


mimo
  • 6,221
  • 7
  • 42
  • 50