[英]nestjs can't inject dependency in custom decorator
In offical document about authorization , i follow this guide and use casl
lib在有关授权的官方文档中,我遵循本指南并使用
casl
lib
Let's assume that if i want to validate the request man is the owner of an article, i must get the article data from the database, and compare userId
between user
and article.userId
, so i must inject a repoistory dependency like this假设如果我想验证请求 man 是一篇文章的所有者,我必须从数据库中获取文章数据,并在
user
和article.userId
之间比较userId
,所以我必须像这样注入一个 repoistory 依赖项
@Injectable()
export class DeleteHolePolicyHandler implements IPolicyHandler {
@Inject()
private readonly treeholeDaoService: TreeholeDaoService
async handle(ability: AppAbility, req: Request) {
const hole = await this.treeholeDaoService.findById(req.body.id)
return res
}
}
but i got an error, it shows me this.treeholeDaoService
is undefined.但我收到一个错误,它显示
this.treeholeDaoService
未定义。
so what should i do that can make it work?那么我应该怎么做才能让它工作呢?
this is reproduce link这是复制链接
You can't inject dependencies since it's an in-place property declared using new.您不能注入依赖项,因为它是使用 new 声明的就地属性。 As stated in the docs :
如文档中所述:
Since we must instantiate the policy handler in-place using the new keyword,
ReadArticlePolicyHandler
class cannot use the Dependency Injection.由于我们必须使用 new 关键字就地实例化策略处理程序,
ReadArticlePolicyHandler
class 不能使用依赖注入。 This can be addressed with theModuleRef#get
method (read more here ).这可以通过
ModuleRef#get
方法解决(在此处阅读更多内容)。 Basically, instead of registering functions and instances through the@CheckPolicies()
decorator, you must allow passing aType<IPolicyHandler>
.基本上,您必须允许传递一个
Type<IPolicyHandler>
,而不是通过@CheckPolicies()
装饰器注册函数和实例。 Then, inside your guard, you could retrieve an instance using a type reference:moduleRef.get(YOUR_HANDLER_TYPE)
or even dynamically instantiate it using the ModuleRef#create method.然后,在您的守卫内部,您可以使用类型引用检索实例:
moduleRef.get(YOUR_HANDLER_TYPE)
,甚至可以使用 ModuleRef#create 方法动态实例化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.