问题
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