成分是否可注射? [英] Component as Injectable?
问题描述
我正在尝试构建自己的Modal组件,以便能够在我的Angular2 Apps中重用.我正在考虑不同的方法,并且想知道是否可以创建同时用作@Injectable
的@Component
?我正在考虑这一点,因为我想为Modal构建一个模板,并将其放在一个位置.
I am trying to build my own Modal component, that I would be able to reuse throughout my Angular2 Apps. I am considering different approaches, and I am wondering if it is possible to create @Component
that also serves as @Injectable
? I am considering this, as I want to build a template for the Modal, and keep it in one place.
谢谢
推荐答案
默认情况下,一个组件可以注入@Component()
(或@Directive()
)包括@Injectable()
.
A component is injectable by default @Component()
(or @Directive()
) includes @Injectable()
.
不要期望获得注入组件的特定实例.例如,这适用于constructor(@Host() private parentComponent)
,其中DI查找仅限于父注入器,直至宿主元素的注入器.
Don't expect to get a specific instance of a component injected. This works for example with constructor(@Host() private parentComponent)
where DI lookup is limited to parent injectors up to the injector of the host element.
通常在您的用例中使用DynamicComponentLoader
,它仅接受组件的类型,而不接受实例的类型.依赖注入只会创建一个组件类的实例,而不会创建例如关联的视图.
Normally for your use case DynamicComponentLoader
is used which only accepts the type of a component, not an instance. Dependency injection would just create an instance of the components class but not for example the associated view.
这篇关于成分是否可注射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!