我正在尝试将配置数据传递到Angular中的自定义库。
在用户应用中,他们会使用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 {}
在我的自定义库中,特别是index.ts
,我可以访问配置数据:
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]
};
}
}
我的问题是如何在自定义库SampleService
目前SampleService
包含以下内容:
@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);
}
}
我已阅读Providers上的文档,但forRoot
示例非常小,似乎无法涵盖我的用例。
答案 0 :(得分:62)
您几乎就在那里,只需在您的模块中同时提供SampleService
和config
,如下所示:
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 );
}
}