简体   繁体   English

如何使用Angular2将服务注入动态组件

[英]How to inject a service into a dynamic component with Angular2

I have a component that dynamically loads another component using DynamicComponentLoader. 我有一个使用DynamicComponentLoader动态加载另一个组件的组件。 However, the dynamic component needs to have a service injected. 但是,动态组件需要注入服务。 However, I'm unsure how to go about this. 但是,我不确定如何解决这个问题。 I see from Angular.io docs that DynamicComponentLoader accepts a ResolvedProvider array. 我从Angular.io文档中看到DynamicComponentLoader接受ResolvedProvider数组。

I've tried to get a provider by doing: 我试图通过以下方式获得提供商:

var provider = provide(ManagerService, {useExisting: ManagerService});
dcl.loadIntoLocation(this.data.template, this.er, "content",[provider]);

This doesn't seem to work. 这似乎不起作用。 You can see an example on plunker . 你可以在plunker上看到一个例子

On the plunker example, you can see that the Info component loads (because it isn't requiring the service) but the Alternate component won't load. 在plunker示例中,您可以看到Info组件加载(因为它不需要服务),但Alternate组件将不会加载。

I'm a little confused because the service is being injected at the root component so I thought that it would automatically be injected on every child component when it was called for. 我有点困惑,因为服务是在根组件注入的,所以我认为它会在被调用时自动注入每个子组件。

How do I get this service injected? 如何注入此服务?

It shouldn't be any different than normal DI 它不应该与正常的DI有任何不同

this.dynamicComponentLoader.loadIntoLocation(MyComponent, this.elementRef, "content")


class MyComponent{
  constructor(someService:SomeService){}//injected here when instantiated
}

If your dynamically loaded component injects services in the constructor it works like normal DI. 如果动态加载的组件在构造函数中注入服务,它就像普通的DI一样工作。

Make sure the service is registered in some provider array though. 确保服务已在某些提供程序数组中注册。 Either at the component level or higher up in the chain (parent or bootstrap) 在链中的组件级别或更高级别(父级或引导程序)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM