【问题标题】:NestJS: How to setup ClassSerializerInterceptor as global interceptorNestJS:如何将 ClassSerializerInterceptor 设置为全局拦截器
【发布时间】:2019-09-07 06:44:53
【问题描述】:

我在每个控制器代码中都使用@UseInterceptors(ClassSerializerInterceptor),因此我决定将其设为全局并尝试设置它,但没有运气。

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

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

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

【问题讨论】:

  • 你成功了吗?我也没有找到让它工作的方法。我试过app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));

标签: interceptor nestjs


【解决方案1】:

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

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

【讨论】:

  • 不会工作,因为ClassSerializerInterceptor 需要提供适当的构造函数参数
  • 好吧,这是真的! ClassSerializerInterceptor 需要一个 Reflector 实例才能正确实例化
  • @G.Bar 我更新了我的答案,也许它适合你的情况。告诉我。
【解决方案2】:

我更喜欢在 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 {}

参考:

How to use Service in Global-interceptor in NEST Js

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 2021-08-08
    • 2020-08-30
    • 2020-01-03
    • 2020-12-12
    • 2020-06-29
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多