Angular2:实例级别的依赖注入

时间:2017-03-07 00:14:03

标签: angular

(对不起,下一段很难解析。我发现在描述DI时总会发生这种情况。)

我有一个现有的组件,称之为Widget

Widget通过ng2 DI收到Thingy。反过来,Thingy会通过DI收到ThingyPart

现在我正在编写一个新组件,称之为WidgetListWidgetList最终将进入循环并创建多个Widget。关于这些Widget中的每一个的主要不同之处在于,每个ThingyPart都需要注入不同的Thingy WidgetListWidgetList,只有ThingyPart知道如何构造那些ThingyPart,并且它需要当前的循环变量才能构造。

最终需要发生的是我需要为每个循环迭代提供不同的Widget。有没有办法在不触及from OpenSSL import SSL 的情况下实现这一目标?

替代问题:我注意到我可以在我的WidgetList中receive the raw Injector。有没有办法动态添加和删除我的viewchildren使用注入器API看到的子注入器?如果有,那么我可以在循环中创建一个新的子注入器并删除旧的子注入器。 (你知道什么会很酷吗?一个“提供”模板指令,为我做这件事。)

1 个答案:

答案 0 :(得分:1)

听起来像在WidgetList组件中,您需要提供ThingyPart作为工厂。然后,您可以使用WidgetList中的数据创建ThingyPart的实例。

例如

  @Component({
     selector: 'widget-list',
    .....
    providers: [
      { provide: ThingConfigService, useFactory: (widget ) => {
         ...  // use the Widget here to configure ThingConfigService as you need
              // then you can use ThingConfigService within your ThingyPart
              // and pull out the data that you need
         }, deps: [ Widget ]   
      }
    ]
 ......

useFactory选项接受可以返回已配置的ThingyPart的函数。如果不了解你想要完成的更多内容,很难引导你进一步。

Thoughtram has an article about dependency injection that may prove useful