如何使用 ConfigService 中的变量初始化 RouterModule?
我想使用 RouterModule.register(arrayOfRoutes),但我需要使用 ConfigService 中的变量构建 arrayOfRoutes。
这样做的正确方法是什么?
感谢您的帮助! ;)
// current state, appRoutes is not customizable.
// app.routes.ts
export const appRoutes: Routes = [
{ path: RouteEnum.EndpointA, module: EndpointAModule },
{ path: RouteEnum.EndpointB, module: EndpointBModule },
];
// app.module.ts
@Module({
imports: [
ConfigModule.forRoot({ load: loadConfiguration(), cache: true, isGlobal: true }),
RouterModule.register(appRoutes)
],
})
export class AppModule {}
我想使用这样的服务:
// routes.service.ts
@Injectable()
export class RoutesService {
#routes: Routes = [
{ path: RouteEnum.EndpointA, module: EndpointAModule },
{ path: RouteEnum.EndpointB, module: EndpointBModule },
];
constructor(private readonly configService: ConfigService) {
if (this.configService.get('endpoint-c')?.enabled === true) {
this.#routes.push({ path: RouteEnum.EndpointC, module: EndpointCModule });
}
}
getRoutes(): RouteTree[] {
return this.#routes;
}
}
I want to use the RouterModule.register(arrayOfRoutes), but I need to build the arrayOfRoutes with a variable from the ConfigService.
What is the proper way to do that ?
Thanks for the help ! ;)
// current state, appRoutes is not customizable.
// app.routes.ts
export const appRoutes: Routes = [
{ path: RouteEnum.EndpointA, module: EndpointAModule },
{ path: RouteEnum.EndpointB, module: EndpointBModule },
];
// app.module.ts
@Module({
imports: [
ConfigModule.forRoot({ load: loadConfiguration(), cache: true, isGlobal: true }),
RouterModule.register(appRoutes)
],
})
export class AppModule {}
I’d like to use some kind of service like this :
// routes.service.ts
@Injectable()
export class RoutesService {
#routes: Routes = [
{ path: RouteEnum.EndpointA, module: EndpointAModule },
{ path: RouteEnum.EndpointB, module: EndpointBModule },
];
constructor(private readonly configService: ConfigService) {
if (this.configService.get('endpoint-c')?.enabled === true) {
this.#routes.push({ path: RouteEnum.EndpointC, module: EndpointCModule });
}
}
getRoutes(): RouteTree[] {
return this.#routes;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它是这样结束的:
@Controller('some_route')
装饰器在调用 AppModule 之前处理配置。注册是我们想做的。
It ended like this :
@Controller('some_route')
decorator directly in the controllersHandling the configuration before calling AppModule.register is what we wanted to do.