【发布时间】:2017-09-03 16:40:11
【问题描述】:
我正在尝试将配置数据传递到 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 的示例非常少,似乎没有涵盖我的用例。
【问题讨论】:
-
您能否将地图传递给您的自定义配置?像这样 myMap: Map
;我正在尝试传递地图,但如果我打开 AOT (ng serve --AOT) 则它不起作用
标签: angular typescript angular2-services angular2-aot