初始化后卫值
是否有可能与一个特定的值来初始化后卫?例如,当前示例将无法正常工作:
@Module({
imports: [
CoreModule,
],
providers: [
{
provide: AuthGuard, // while using APP_GUARD works
useFactory: (configService: ConfigService) => {
return new AuthGuard(configService.get('some_key'));
},
inject: [ConfigService],
},
],
})
在使用APP_GUARD
为provide
将与初始化配置值的后卫。因此,它仅适用于全球范围内,但不适合@UseGuards(AuthGuard)
这不起作用,因为警卫没有注册为模块供应商。他们得到直接由框架实例化。
您可以使用依赖注入在中后卫:
@Injectable()
export class MyAuthGuard {
constructor(private readonly configService: ConfigService) {
// use the configService here
}
}
和
@UseGuards(MyAuthGuard)
或者你自己的实例后卫:
@UseGuards(new AuthGuard(configService.get('some_key')))
在AuthGuard
的特殊情况下,可以设置在defaultStrategy
一个PassportModule
。然后,你可以只使用@UseGuards(AuthGuard())
PassportModule.register({ defaultStrategy: 'jwt'})
或异步:
PassportModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ defaultStrategy: configService.authStrategy}),
inject: [ConfigService],
})