我想使用在其他模块中定义的提供程序值。以下是示例:
应用程序模块.ts
...
import { ThemeModule } from '../shared/modules/theme/theme.module';
...
@NgModule({
declarations: [
RootComponent,
LoginScreenComponent,
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
BrowserAnimationsModule,
AppRoutingModule,
ConfigModule,
ThemeModule,
....
],
providers: [
...
{ provider: "THEME_NAME", useValue: "VALUE" },
],
bootstrap: [RootComponent]
})
export class MDMToolModule {}
主题模块.ts
import { NgModule } from '@angular/core';
import { ThemeService } from './services/ThemeService';
@NgModule({
imports: [],
declarations: [],
providers: [
{provide: "ThemeService", useFactory: (THEME_NAME) => {
return new ThemeService(THEME_NAME)
}},
],
exports: []
})
export class ThemeModule {}
是否有可能传递模块中未定义的VALUE(THEME NAME(?
如果您在根模块中提供值,那么它也将可用于所有其他模块,因此您可以简单地使用Inject-decorator来请求该值,如下所示:
@Injectable()
export class ThemeService {
constructor(@Inject("THEME_NAME") theme: string) {}
}
否则,您可以在ThemeModule
中导入您的MDMToolModule
,尽管根据您提供的代码判断,我假设这个MDMToolModule
是您的根模块,你也可以使用注入令牌来避免使用像这样的魔术串:
const ThemeName = new InjectionToken("token to inject theme name");
然后在主题模块.ts中使用
@NgModule({
providers: [
{ provide: ThemeName, useValue: "DarkKnight" },
ThemeService
]
})
export class ThemeModule {}
主题服务.ts
@Injectable()
export class ThemeService {
constructor(@Inject(ThemeName) theme: string) {}
}