角 |将服务注入装饰器 [英] Angular | Inject service into decorator

查看:25
本文介绍了角 |将服务注入装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将服务注入到我正在创建的装饰器函数中,这样我就可以获取存储在变量中的内容.

I am trying to inject a service into a decorator function in which I am creating, this is so I can get the contents that are stored inside of variables.

我目前有一个基本的装饰器设置.

I currently have a basic decorator setup.

export function canEdit(editName: string, service: Service) {
      return function (constructor: any) {
          console.log(constructor);
      }
}

在我使用它的地方,它要求我提供第二个参数,这显然需要依赖注入.

Where I am using this it is asking me for the second parameter, which obviously needs to be dependency injected.

我还尝试了函数中不允许使用的 @Inject(Service).

I have also tried the @Inject(Service) which isn't allowed within functions.

有没有办法做到这一点?

Is there a way that I can do this?

或者是否可以在装饰器中获取父类变量?

Or is it possible to get the parent classes variables within the decorator?

推荐答案

装饰器是一种 TypeScript 功能,可在 Angular 的依赖注入系统之外工作.

Decorators are a TypeScript feature that work outside of Angular's dependency injection system.

我所知道的唯一解决方案是创建一个特殊的服务,该服务将向装饰器公开依赖项.

The only solution that I know of is to create a special service that will expose dependencies to the decorator.

@Injectable()
export class DecoratorService {
     private static service: Service | undefined = undefined;
     public constructor(service: Service) {
         DecoratorService.service = service;
     }
     public static getService(): Service {
         if(!DecoratorService.service) {
             throw new Error('DecoratorService not initialized');
         }
         return DecoratorService.service;
     }
}

您现在可以通过上述类访问注入的服务.

You can now access the injected service via the above class.

export function canEdit(editName: string) {
      return function (constructor: any) {
          const service = DecoratorService.getService();
          // ^^^ access dependency here
          console.log(constructor);
      }
}

除非 Angular 应用程序中的某些内容依赖于 DecoratorService,否则上述内容将不起作用,因为 Angular 会在需要时创建实例.所以你可以将它注入到一个模块中来强制它被初始化.

The above will not work unless something in the Angular application depends upon DecoratorService because Angular creates instances when they are needed. So you can inject it into a module to force it to be initialized.

@NgModule({
    provides: [
        DecoratorService
    ]
})
export class MainModule {
    public constructor(service: DecoratorService) {
                      // ^^^ forces an instance to be created
    }
}

这篇关于角 |将服务注入装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆