Angular 4 Custom decorator - injecting services

前端 未结 1 960
借酒劲吻你
借酒劲吻你 2021-02-09 02:21

I want to create authentication decorator in my application.

Call should be simple as

@RequireAuthentication()
@HostListener(\'click\', [\'$event\']) on         


        
相关标签:
1条回答
  • 2021-02-09 03:02

    As explained in this answer, the solution that is idiomatic to the framework is to expose injector class instance property, so it could be accessed inside decorator. The existence of injector property can be also secured with an interface.

    Since property decorator runs once and has access to class prototype but not instance, it's necessary to patch ngOnOnit method and retrieve all necessary services inside patched method with this.injector.get().

    The alternative is to expose global injector to some object, as explained here. This is not idiomatic solution but a hack that will result in certain limitations and negative consequences. It can hardly be recommended for use in production.

    0 讨论(0)
提交回复
热议问题