How to inject a service into a dynamic component with Angular2
Asked Answered
A

1

4

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?

Alumina answered 8/4, 2016 at 2:29 Comment(0)
L
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)

Lima answered 8/4, 2016 at 3:56 Comment(1)
That's what I thought. Did you have a look at the plunker example. As you can see, it clearly isn't being injected and as far as I can see, I've set everything up correctly.Alumina

© 2022 - 2024 — McMap. All rights reserved.