Angular 2-将依赖项注入装饰器工厂 [英] Angular 2 - Inject a dependency into a decorator factory
问题描述
是否有一种使用Angular的DI将依赖项注入到装饰器工厂的方法?让我们以下面的代码为简化示例:
Is there a way to inject a dependency into a decorator factory, using Angular's DI? Let's take the following code as a simplified example:
@Component({
selector: 'hello-component',
template: '<div>Hello World</div>'
})
export class HelloComponent {
@PersonName()
name: string;
ngAfterViewInit() {
console.log(`Hello, ${this.name}`);
}
}
在这里,PersonName
装饰器的预期行为是让它访问Person
依赖项,并使用它来设置类的name
属性.
Here, the intended behaviour of the PersonName
decorator is for it to access a Person
dependency, and use it to set the name
property of the class.
是否可以为上面的代码实现PersonName
装饰器?
Is it possible at all to implement the PersonName
decorator for the code above?
推荐答案
当前,要将依赖项注入到我的装饰器(以及其他额外的模块类)中,我正在使用以下解决方法:
Currently, to inject dependencies into my decorators (and other extra module classes) I'm using this workaround:
import {Injectable, Injector} from "@angular/core";
@Injectable()
export class ExtraModuleInjector {
private static injector;
public static get(token: any) {
if (ExtraModuleInjector.injector) {
return ExtraModuleInjector.injector.get(token);
}
}
constructor(public injector: Injector) {
ExtraModuleInjector.injector = injector;
}
}
在注入到根组件之后,它允许在运行时函数执行期间使用静态get方法获取依赖项. 仍在寻找更好的解决方案.
After being injected to root component, it allows to use static get method to get dependencies during runtime functions execution. Still looking for better solution.
这篇关于Angular 2-将依赖项注入装饰器工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!