Roi*_*oip 8 angular angular-library angular-dependency-injection
我创建了两个 Angular 库,其中一个库依赖另一个库。
需要使用 forRoot 方法配置依赖关系。我如何将配置数据从父库传递到它的依赖项?
例如,假设我们有TopLevelLib,它有OtherLib一个依赖项。需要使用 forRoot 向 OtherLib 传递一个配置对象。
最终用户的AppModule,导入到
@NgModule({
imports: [
TopLevelLib.forRoot(someConfigData)
],
declarations: [...],
exports: [...]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
TopLevelLib - 由最终用户导入到 AppModule
@NgModule({
imports: [
...
OtherLib.forRoot(*****what goes in here?*****)
],
declarations: [...],
exports: [...]
})
export class TopLevelLib {
static forRoot(config: ConfigObj): ModuleWithProviders {
return {
ngModule: SampleModule,
providers: [{ provide: SomeInjectionToken, useValue: config }]
};
}
}
Run Code Online (Sandbox Code Playgroud)
OtherLib - 由 TopLevelLib 导入
@NgModule({
imports: [...],
declarations: [...],
exports: [...]
})
export class OtherLib {
static forRoot(config: ConfigObj): ModuleWithProviders {
return {
ngModule: SampleModule,
providers: [{ provide: SomeInjectionToken, useValue: config }]
};
}
}
Run Code Online (Sandbox Code Playgroud)
我需要的是将配置对象实例从 TopLevelLib 传递到 OtherLib。这样,当最终用户使用 forRoot 配置 TopLevelLib 时,OtherLib 将配置相同的数据。
关于如何实现这一点有什么想法吗?
您可以输入forRoot参数。您已明确定义OtherLibhasconfig: ConfigObj作为参数 - 这意味着TopLevelLib需要使用 的实例来配置它ConfigObj。所以评论的答案*****what goes in here?*****是: 的一个实例ConfigObj。
编辑:评论后,您似乎想传递一些配置值。你可以这样做:
export class TopLevelLib {
static forRoot(config: ConfigObj): ModuleWithProviders {
return {
ngModule: SampleModule,
providers: [{ provide: ConfigObj, useValue: config }]
};
}
}
Run Code Online (Sandbox Code Playgroud)
然后OtherLib可以使用 Injector 来获取:
class OtherLib {
constructor(@Inject() ConfigObj) {}
...
Run Code Online (Sandbox Code Playgroud)