【发布时间】:2020-02-18 06:57:38
【问题描述】:
我喜欢按照功能线组织我的项目,使用不同的模块来解决横切关注点,例如:配置、身份验证等。但是,当将 Interceptor 导入功能模块以与 Controller 一起使用时,Nest 似乎没有重用现有实例。
controllers.module.ts
@Module({
imports: [
// ConfigService is exported from this module.
ConfigModule
],
providers: [
// For debugging purposes I used a factory so I could place a breakpoint and see
// when the Interceptor is being created.
{
provide: MyInterceptor,
useFactory: (config: ConfigService) => new MyInterceptor(config),
inject: [
ConfigService
]
}
],
exports: [
MyInterceptor
]
})
export class ControllersModule {
}
customer.module.ts
@Module({
imports: [
ControllersModule
],
controllers: [
CustomerController
],
providers: [
CustomerService
]
})
export class CustomerModule {
}
customer.controller.ts
@Controller("/customers")
@UseInterceptors(MyInterceptor)
export class CustomerController {
constructor(private readonly customerService: CustomerService) {
}
@Get()
customers() {
return this.customerService.findAll();
}
}
当应用程序启动时,我可以看到MyInterceptor 提供程序工厂被调用,其中有一个ConfigService 的实例。但是然后我在控制台上看到以下错误
error: [ExceptionHandler] Nest can't resolve dependencies of the MyInterceptor (?). Please make sure that the argument ConfigService at index [0] is available in the CustomerModule context.
Potential solutions:
- If ConfigService is a provider, is it part of the current CustomerModule?
- If ConfigService is exported from a separate @Module, is that module imported within CustomerModule?
@Module({
imports: [ /* the Module containing ConfigService */ ]
})
现在也许有一些关于 Nest 如何实例化/使用拦截器的事情我不理解,但我认为鉴于 MyInteceptor 已创建,并且 CustomerModule 导入的 ControllersModule bean 将可用并申请到CustomerController。
这里有什么我遗漏的吗?
【问题讨论】:
标签: nestjs