1

I have a module (lets say module A) that imports another module (module B), that gets parameters though its forRoot.

@NgModule({
  declarations: [AComponent, XComponent],
  imports: [
    BrowserModule,
    ModuleB.forRoot({
      apiKey: 'api-key-here',
    }),
  ],
  providers: [],
  bootstrap: [AComponent],
  exports: [AComponent],
})
export class ModuleA {}

ModuleA is going to be installed via npm and used in all kinds of different projects. I would like each user of ModuleA to provide his own api key that will be passed into the internal ModuleB for use.

My researched yielded that the best way is to implement a forRoot for ModuleA, that will accept a config object containing the api key.

However, I could not find (via research or trial-and-error) how to pass that api key to the forRoot of ModuleB.

Any advice? Thanks!

Zephyer
  • 333
  • 6
  • 16
  • Have you thought of providing `apiKey` as an injectable token? This way it can be shared across all the components everywhere in the application. You could use `provide: TOKEN, useValue: 'your value'` – Yevhenii Dovhaniuk Nov 11 '20 at 14:42
  • @YevheniiDovhaniuk I'm not sure this fits my use-case, because I need to use the config immediately at ModuleA's "setup" in the `forRoot` of ModuleB in the imports. – Zephyer Nov 11 '20 at 15:58
  • You are probably understanding the `forRoot` in an incorrect way. `forRoot` is used to make the provided services as singletons and has nothing to do with module's init phase. If you want to provide the `apiKey` once - simply export it by the `ApiModule` (where you can have the `forRoot` or whatever `provide` logic you want) and make other modules depend on the `ApiModule` – Yevhenii Dovhaniuk Nov 12 '20 at 12:34

0 Answers0