NestJS-在拦截器不是全局拦截器内部使用服务

问题描述

我有一个使用自定义拦截器的控制器:

控制器:

@UseInterceptors(SignInterceptor)
    @Get('users')
    async findOne(@Query() getUserDto: GetUser) {
        return await this.userService.findByUsername(getUserDto.username)
    }

我还有I SignService,它是nestJwt的包装器:

SignService模块:

@Module({
    imports: [
        JwtModule.registerasync({
            imports: [ConfigModule],useFactory: async (configService: ConfigService) => ({
                privateKey: configService.get('PRIVATE_KEY'),publicKey: configService.get('PUBLIC_KEY'),signoptions: {
                    expiresIn: configService.get('JWT_EXP_TIME_IN_SECONDS'),algorithm: 'RS256',},}),inject: [ConfigService],],providers: [SignService],exports: [SignService],})
export class SignModule {}

最后是SignInterceptor:

@Injectable()
export class SignInterceptor implements nestInterceptor {
    intercept(context: ExecutionContext,next: CallHandler): Observable<any> {
        return next.handle().pipe(map(data => this.sign(data)))
    }

    sign(data) {
        const signed = {
            ...data,_signed: 'signedContent',}

        return signed
    }
}

SignService可以正常使用,我可以使用它。我想用它作为拦截器 如何将SignService注入SignInterceptor,以便可以使用它提供的功能

解决方法

我认为SignInterceptorApiModule的一部分:

@Module({
  imports: [SignModule],// Import the SignModule into the ApiModule.
  controllers: [UsersController],providers: [SignInterceptor],})
export class ApiModule {}

然后将SignService注入到SignInterceptor中:

@Injectable()
export class SignInterceptor implements NestInterceptor {
  constructor(private signService: SignService) {}

  //...
}

因为您使用@UseInterceptors(SignInterceptor)在控制器中使用拦截器,所以Nestjs会为您实例化SignInterceptor并处理依赖项的注入。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...