Mic*_*oye 43 typescript angular2-services angular2-aot angular
我试图将配置数据传递到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 {}
Run Code Online (Sandbox Code Playgroud)
在我的自定义库中,特别是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]
};
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在自定义库中提供配置数据 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经阅读了关于提供商的文档,但是这个forRoot例子很小,似乎并不涵盖我的用例.
Gün*_*uer 71
你是几乎没有,只需同时提供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}]
};
}
}
Run Code Online (Sandbox Code Playgroud)
@Injectable()
export class SampleService {
foo: string;
constructor(@Inject('config') private config:CustomConfig) {
this.foo = ThirdParyAPI( config );
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12996 次 |
| 最近记录: |