Pass configuration data to a dependency of a angular library using "forRoot"

Viewed 2429

I've created two Angular libraries, one has the other as a dependency.

the dependency needs to be configured using the forRoot method. how can i pass the configuration data from the parent library to it's dependency?

for example, let's say we have TopLevelLib, which has OtherLib as a dependency. OtherLib needs to be passed a configuration object using forRoot.

End user's AppModule, imports to

@NgModule({
  imports: [
    TopLevelLib.forRoot(someConfigData)
  ],
  declarations: [...],
  exports: [...]
})
export class AppModule { }

TopLevelLib - imported to AppModule by the end user

@NgModule({
  imports: [
    ...
    OtherLib.forRoot(*****what goes in here?*****)
  ],
  declarations: [...],
  exports: [...]
})
export class TopLevelLib {
  static forRoot(config: ConfigObj): ModuleWithProviders {
    return {
      ngModule: SampleModule,
      providers: [{ provide: SomeInjectionToken, useValue: config }]
    };
  }
}

OtherLib - imported by TopLevelLib

@NgModule({
  imports: [...],
  declarations: [...],
  exports: [...]
})
export class OtherLib {
  static forRoot(config: ConfigObj): ModuleWithProviders {
    return {
      ngModule: SampleModule,
      providers: [{ provide: SomeInjectionToken, useValue: config }]
    };
  }
}

What i need is to pass the configuration object instance from TopLevelLib to OtherLib. So that when the end user configures TopLevelLib using forRoot, OtherLib will be configured with the same data.

Any ideas on how to implement this?

2 Answers

You can make your forRoot parameters typed. You have explicitly defined that OtherLib has config: ConfigObj as a parameter - that means that the TopLevelLib needs to configure it with an instance of ConfigObj. So the answer to *****what goes in here?***** comment is: an instance of ConfigObj.

Edit: after comments, you seem to want to pass-through some config value. You can do it this way:

export class TopLevelLib {
  static forRoot(config: ConfigObj): ModuleWithProviders {
    return {
      ngModule: SampleModule,
      providers: [{ provide: ConfigObj, useValue: config }]
    };
  }
}

Then the OtherLib can use Injector to get this:

class OtherLib {
  constructor(@Inject() ConfigObj) {}
...

Eventually, i found a good solution. I've exposed the injection token used by the service (in the example above, OtherLib), imported it to the TopLevelLib module, and provided it to the module instance using the forRoot configuration.

Related