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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…