简体   繁体   English

nestjs 无法在自定义装饰器中注入依赖项

[英]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 是一篇文章的所有者,我必须从数据库中获取文章数据,并在userarticle.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 the ModuleRef#get method (read more here ).这可以通过ModuleRef#get方法解决(在此处阅读更多内容)。 Basically, instead of registering functions and instances through the @CheckPolicies() decorator, you must allow passing a Type<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM