dependency-injection – Angular 2 – 将依赖项注入装饰器工厂
发布时间:2020-12-17 07:25:33 所属栏目:安全 来源:网络整理
导读:有没有办法使用Angular的DI将依赖注入装饰器工厂?我们将以下代码作为简化示例: @Component({ selector: 'hello-component',template: 'divHello World/div'})export class HelloComponent { @PersonName() name: string; ngAfterViewInit() { console.log(
有没有办法使用Angular的DI将依赖注入装饰器工厂?我们将以下代码作为简化示例:
@Component({ selector: 'hello-component',template: '<div>Hello World</div>' }) export class HelloComponent { @PersonName() name: string; ngAfterViewInit() { console.log(`Hello,${this.name}`); } } 这里,PersonName装饰器的预期行为是它访问Person依赖项,并使用它来设置类的name属性. 是否有可能为上面的代码实现PersonName装饰器?
目前,要将依赖项注入我的装饰器(以及其他额外的模块类),我正在使用此解决方法:
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方法在运行时函数执行期间获取依赖关系.仍在寻找更好的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |