在控制器上使用导入的拦截器在NestJS中不起作用

时间:2020-02-18 06:57:38

标签: nestjs

我喜欢按照要素线来组织项目,并使用不同的模块来解决横切关注点,例如:配置,身份验证等。但是,将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已创建,而ControllersModule导入的CustomerModule该bean将会已经可用并应用于CustomerController

这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:0)

拦截器(以及其他请求生命周期类)与pseudoproviders类似,它们是@Injectable(),但不会添加到providers数组中进行绑定。您可以bind then via the providers array,(APP_INTERCEPTOR),但这将导致它被全局绑定。

由于无法按照您尝试的方式将拦截器添加到providers数组中,因此您需要将ConfigModule添加到使用拦截器的任何模块中。

相关问题