如何在NestJS中使用多个全局拦截器

我已经知道我们可以从下面的代码创建全局拦截器:

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

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
  ],
})
export class AppModule {}

来源:文档

但是,如果我想说,UserInterceptor.
UserInterceptor将从数据库中获取用户并转换请求。
UserInterceptor需要注入让说UserService
我想在UserInterceptor全球范围内使用。

@Injectable()
export class UserInterceptor {
  constructor(private readonly service: UserService) {}
}

从文档中,我们不能这样做,app.useGlobalInterceptors(new UserInterceptor())因为UserInterceptor在构造函数 (UserService) 中需要 1 个参数。

而且由于我们使用了APP_INTERCEPTORfor LoggingInterceptor,我没有找到另一种方法来分配另一个值来APP_INTERCEPTOR全局使用拦截器。
例如,我认为如果我们可以这样做,问题就会解决:

providers: [
  {
    provide: APP_INTERCEPTOR,
    useClass: [LoggingInterceptor, UserInterceptor]
  }
]

回答

providers: [
  {
    provide: APP_INTERCEPTOR,
    useClass: LoggingInterceptor
  },
  {
    provide: APP_INTERCEPTOR,
    useClass: UserInterceptor
  }
]

像这样


以上是如何在NestJS中使用多个全局拦截器的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>