可以用一个指定的值来初始化防护吗?例如,当前示例将不起作用:
@Module({
imports: [
CoreModule,
],
providers: [
{
provide: AuthGuard, // while using APP_GUARD works
useFactory: (configService: ConfigService) => {
return new AuthGuard(configService.get('some_key'));
},
inject: [ConfigService],
},
],
})而使用provide的APP_GUARD将使用配置值初始化保护。因此它只适用于全局范围,而不适用于@UseGuards(AuthGuard)
发布于 2019-02-06 16:01:42
这不起作用,因为卫兵没有在模块中注册为提供者。它们由框架直接实例化。
您可以在保护中使用依赖注入:
@Injectable()
export class MyAuthGuard {
constructor(private readonly configService: ConfigService) {
// use the configService here
}
}和
@UseGuards(MyAuthGuard)或者自己实例化卫士:
@UseGuards(new AuthGuard(configService.get('some_key')))在AuthGuard的特殊情况下,您可以在PassportModule中设置defaultStrategy。然后,您可以只使用@UseGuards(AuthGuard())
PassportModule.register({ defaultStrategy: 'jwt'}) 或异步:
PassportModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({ defaultStrategy: configService.authStrategy}),
inject: [ConfigService],
}) 发布于 2019-02-06 15:53:17
我会尝试一种不太冗长的方法,并以这种方式将ConfigService直接注入到AuthGuard中:
@Module({
imports: [
CoreModule,
],
providers: [
AuthGuard,
],
exports: [
AuthGuard,
],
})@Injectable()
export default class AuthGuard {
constructor (protected readonly config: ConfigService) {
}
/*
...
*/
}https://stackoverflow.com/questions/54548743
复制相似问题