15 decorator typescript angular
我正在尝试将服务注入到我正在创建的装饰器函数中,这样我就可以获得存储在变量中的内容。
我目前有一个基本的装饰器设置。
export function canEdit(editName: string, service: Service) {
return function (constructor: any) {
console.log(constructor);
}
}
Run Code Online (Sandbox Code Playgroud)
我在哪里使用它是要求我提供第二个参数,这显然需要依赖注入。
我也尝试过@Inject(Service)函数中不允许的。
有没有办法做到这一点?
或者是否可以在装饰器中获取父类变量?
Ric*_*cky 18
我知道我迟到了,但是,还有另一种方法可以访问装饰器中的服务。
在需要必要服务的模块中暴露 Angular 的 Injector:
@NgModule({
declarations: [],
imports: [],
providers: [SomeService]
})
export class SharedModule {
static injector: Injector;
constructor(injector: Injector) {
SharedModule.injector = injector;
}
}
Run Code Online (Sandbox Code Playgroud)
通过模块注入器属性从装饰器内部获取服务:
export const MyDecorator = (): any => {
return (target: object, key: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor => {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]): any {
// access the service
const service = SharedModule.injector.get<SomeService>(SomeService);
// (...)
};
return descriptor;
};
};
Run Code Online (Sandbox Code Playgroud)
Rea*_*lar 12
装饰器是一种 TypeScript 功能,它在 Angular 的依赖注入系统之外工作。
我所知道的唯一解决方案是创建一个特殊的服务,该服务将向装饰器公开依赖项。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
您现在可以通过上述类访问注入的服务。
export function canEdit(editName: string) {
return function (constructor: any) {
const service = DecoratorService.getService();
// ^^^ access dependency here
console.log(constructor);
}
}
Run Code Online (Sandbox Code Playgroud)
除非 Angular 应用程序中的某些内容依赖,否则上述内容将不起作用,DecoratorService因为 Angular 在需要时创建实例。因此,您可以将其注入模块以强制对其进行初始化。
@NgModule({
provides: [
DecoratorService
]
})
export class MainModule {
public constructor(service: DecoratorService) {
// ^^^ forces an instance to be created
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7459 次 |
| 最近记录: |