NestJS:如何将 ClassSerializerInterceptor 设置为全局拦截器

G. *_*Bar 7 interceptor nestjs

我在每个控制器代码中都使用了@UseInterceptors(ClassSerializerInterceptor)这样的代码,所以我决定将其设为全局,并试图在没有运气的情况下进行设置。

我在没有和有的情况下尝试过new,结果这样的事情完全不起作用。

app.useGlobalInterceptors(new ClassSerializerInterceptor(new Reflector()));

我检查了 NestJS 源代码,我认为它不能用作全局,但它应该。

A. *_*tre 30

您是否尝试过使用这行代码:

app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
Run Code Online (Sandbox Code Playgroud)

  • 不起作用,因为“ClassSerializerInterceptor”需要提供正确的构造函数参数 (2认同)
  • @G.Bar 我更新了我的答案,也许它适合你的情况。让我知道。 (2认同)

Chr*_* So 19

我确实更喜欢在内部注入全局拦截器app.modules.ts

从任何模块外部注册的全局拦截器useGlobalInterceptors()无法注入依赖项,因为这是在任何模块的上下文之外完成的。

import { ClassSerializerInterceptor, Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: ClassSerializerInterceptor,
    },
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

参考:

如何在NEST Js中使用全局拦截器中的服务

https://docs.nestjs.com/interceptors#binding-interceptors