在指令中手动获取Injector的依赖关系 [英] Getting dependency from Injector manually inside a directive

查看:170
本文介绍了在指令中手动获取Injector的依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个泛型指令,该指令将采用类类型进行规则验证,并且根据类中的规则,该指令将显示或隐藏元素。

I am trying to create a generic directive which will take a class type for rule validation and according to the rule in the class the directive will either show or hide an element.

这是我到目前为止的尝试。

This is my attempt so far.

PLUNKER 演示

myIf-Directive.ts

@Directive({
  selector: '[myIf]'
})
export class MyIfDirective {
  constructor(private _viewContainer: ViewContainerRef,
    private _template: TemplateRef<Object>) 
  { }

  @Input() set myIf(rule: string) {
    //rule class type will come as string
    //how can I use string token to get dependency from injector?
    //currently harcoded
    //will the injector create new instance or pass on instance from parent?
    let injector = ReflectiveInjector.resolveAndCreate([AdminOnly]);
    let adminOnly : IRule = injector.get(AdminOnly);
    let show = adminOnly.shouldShowElement();
    show ? this.showItem() : this.hideItem();
  }
  private showItem() {
    this._viewContainer.createEmbeddedView(this._template);
  }

  private hideItem() {
    this._viewContainer.clear();
  }
}



app-component.ts

@Component({
  selector: 'my-app',
  template: `
    <div *myIf="'AdminOnly'">
      <h2>Hello {{name}}</h2>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}

但我被困在2个地方:


  1. 我一直收到错误否AuthService的提供者

  2. 我不知道如何使用类名作为字符串而不是类型

  3. 从Injector获取依赖关系
  1. I keep getting the error No Provider for AuthService
  2. I do not know how I can get the dependency from Injector using class name as string rather than the type

我们非常感谢您提出这是否是正确的方法或我出错的地方。

Any suggestion whether this is the right way to do it or where I am going wrong is highly appreciated.

推荐答案

您需要传递父注入器,如

You need to pass the parent injector like

export class MyIfDirective {
  constructor(private injector:Injector, private _viewContainer: ViewContainerRef,
    private _template: TemplateRef<Object>) 
  { }

  @Input() set myIf(rule: string) {
    let resolvedProviders = ReflectiveInjector.resolve([AdminOnly]);
    let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);

    let adminOnly : IRule = childInjector.get(AdminOnly);
    let show = adminOnly.shouldShowElement();
    show ? this.showItem() : this.hideItem();
  }
  private showItem() {
    this._viewContainer.createEmbeddedView(this._template);
  }

  private hideItem() {
    this._viewContainer.clear();
  }
}

另请参阅使用ReflectiveInjector注入服务而不指定依赖关系树中的所有类

这篇关于在指令中手动获取Injector的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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