angulartypescriptangular2-servicesangular2-aot

Pass config data using forRoot


I am trying to pass config data into a custom library in Angular.

In the users application, they will pass some config data to my library using forRoot

// Import custom library
import { SampleModule, SampleService } from 'custom-library';
...

// User provides their config
const CustomConfig = {
  url: 'some_value',
  key: 'some_value',
  secret: 'some_value',
  API: 'some_value'
  version: 'some_value'
};

@NgModule({
  declarations: [...],
  imports: [
    // User config passed in here
    SampleModule.forRoot(CustomConfig),
    ...
  ],
  providers: [
    SampleService
  ]
})
export class AppModule {}

In my custom library, specifically the index.ts, I can access the config data:

import { NgModule, ModuleWithProviders } from '@angular/core';
import { SampleService } from './src/sample.service';
...

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [...],
  exports: [...]
})
export class SampleModule {
  static forRoot(config: CustomConfig): ModuleWithProviders {
    // User config get logged here
    console.log(config);
    return {
      ngModule: SampleModule,
      providers: [SampleService]
    };
  }
}

My question is how do I make the config data available in the custom library's SampleService

Currently SampleService contains the following:

@Injectable()
export class SampleService {

  foo: any;

  constructor() {
    this.foo = ThirdParyAPI(/* I need the config object here */);
  }

  Fetch(itemType:string): Promise<any> {
    return this.foo.get(itemType);
  } 
}

I have read through the docs on Providers, however the forRoot example is quite minimal and doesn't seem to cover my use case.


Solution

  • You are almost there, simply provide both SampleService and config in your module like below:

    export class SampleModule {
      static forRoot(config: CustomConfig): ModuleWithProviders<SampleModule> {
        // User config get logged here
        console.log(config);
        return {
          ngModule: SampleModule,
          providers: [SampleService, {provide: 'config', useValue: config}]
        };
      }
    }
    
    @Injectable()
    export class SampleService {
    
      foo: string;
    
      constructor(@Inject('config') private config:CustomConfig) {
        this.foo = ThirdParyAPI( config );
      }
    }
    

    Update:

    Since Angular 7 ModuleWithProviders is generic, so it needs ModuleWithProviders<SampleService>