本文介绍了NgModule嵌套forRoot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑到有一个模块
@NgModule({
imports: [
Ng2Webstorage.forRoot({ prefix: 'SOME_PREFIX' }),
FooModule.forRoot(...),
BarModule,
],
exports: [
Ng2Webstorage,
FooModule,
BarModule,
]
})
class FeatureModule {
static forRoot(config): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [...]
};
}
}
如何动态地将prefix
传递给Ng2Webstorage.forRoot
?喜欢:
How can it pass prefix
to Ng2Webstorage.forRoot
dynamically? Like:
@NgModule({
imports: [
BarModule,
],
exports: [
Ng2Webstorage,
FooModule,
BarModule,
]
})
class FeatureModule {
static forRoot(config): ModuleWithProviders {
return {
ngModule: FeatureModule,
imports: [
Ng2Webstorage.forRoot({ prefix: config.name }),
FooModule.forRoot(config.foo)
],
providers: [...]
};
}
}
...
imports: [FeatureModule.forRoot({ name: `ANOTHER_PREFIX` }), ...]
...
是否可以嵌套forRoot
调用?
ModuleWithProviders
似乎不接受imports
.
推荐答案
是的,您是对的.我们无法将imports
传递给ModuleWithProviders
导入.
Yes, you're right. We can't pass imports
to ModuleWithProviders
import.
以下是angular如何从此类导入中收集数据的信息:
Here is how angular collects data from such import:
} else if (importedType && importedType.ngModule) {
const moduleWithProviders: ModuleWithProviders = importedType;
importedModuleType = moduleWithProviders.ngModule;
if (moduleWithProviders.providers) {
providers.push(...this._getProvidersMetadata(
moduleWithProviders.providers, entryComponents,
`provider for the NgModule '${stringifyType(importedModuleType)}'`, [],
importedType));
}
https://github.com/angular/angular/blob/4.3.x/packages/compiler/src/metadata_resolver.ts#L448-L456
我们可以覆盖 Ng2Webstorage.forRoot中定义的提供程序()通过在ModuleWithProviders.providers
内传递相同的提供程序,如下所示:
We can override provider declated within Ng2Webstorage.forRoot() by passing the same provider within ModuleWithProviders.providers
like this:
import {Ng2Webstorage, WEBSTORAGE_CONFIG} from 'ngx-webstorage';
@NgModule({
imports: [
Ng2Webstorage.forRoot()
],
...
})
export class FeatureModule {
static forRoot(config): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [
{ provide: WEBSTORAGE_CONFIG, useValue: config }
]
};
}
}
这篇关于NgModule嵌套forRoot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!