Pass config data using forRoot

穿精又带淫゛_ 提交于 2019-11-26 11:59:31

问题


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.


回答1:


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

export class SampleModule {
  static forRoot(config: CustomConfig): ModuleWithProviders {
    // 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 );
  }
}


来源:https://stackoverflow.com/questions/43292628/pass-config-data-using-forroot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!