nestjs - NestJS - 在拦截器中使用服务(不是全局拦截器)
问题描述
我有一个使用自定义拦截器的控制器:
控制器:
@UseInterceptors(SignInterceptor)
@Get('users')
async findOne(@Query() getUserDto: GetUser) {
return await this.userService.findByUsername(getUserDto.username)
}
我也有我的 SignService,它是 NestJwt 的包装器:
标志服务模块:
@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 中,以便可以使用它提供的功能?
解决方案
我认为这SignInterceptor
是以下内容的一部分ApiModule
:
@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
并处理依赖项的注入。
推荐阅读
- java - 使用 ArrayAdapters 时,在单击按钮时将 ListView choiceMode 从 singleChoice 更改为 multipleChoiceModal
- javascript - reactjs路由无法正常工作
- windows - 如何使用groovy打印Windows10的用户定义变量?
- javascript - Vue,有没有办法在没有 URL 参数的路由之间传递数据?
- apache - 如何获取默认的 Apache getting-started.html?
- python-3.x - 如何正确验证 LDAP?
- mysql - MySQL:为什么使用 REPLACE 时 url 不匹配?
- pyspark - Athena 仅更新特定分区:MSCK REPAIR TABLE
- android - 制作一个可以随着屏幕尺寸和 pd 变化而缩放的 ui 的最佳方法是什么?
- php - 从 laravel 5.6 中的 sql 视图中选择