How to inject a service into a dynamic component with Angular2

泄露秘密 提交于 2019-12-07 08:52:20

问题


I have a component that dynamically loads another component using 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.

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.

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.

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?


回答1:


It shouldn't be any different than normal 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.

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)



来源:https://stackoverflow.com/questions/36490509/how-to-inject-a-service-into-a-dynamic-component-with-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!