Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 // Why is DependencyInjection with Generics only working in Components?

I have a service using generics that I would like to inject into another service like this

export class RestoreService<T>

Injection works in components like this

constructor(private restoreService: RestoreService<Hero>) {}

If I try to inject the same service into a non Component class I get an Exception saying "Cannot resolve all parameters for OtherService(?). Make sure they all have valid type or annotations."

Here is a sample sample based on the hierarchical injection sample by angular.io http://plnkr.co/edit/wkj838xacI3cbOvz3qTs?p=preview

I also noticed that injecting multiple instances of RestoreService with different Ts results only in one instance being created. So I wonder if working with generic classes is a recommended pattern at all.

like image 627
Philipp Bauknecht Avatar asked Feb 17 '26 01:02

Philipp Bauknecht


1 Answers

Ensure you have all dependencies registered as providers. Adding for example RestoreService, OtherService to the providers to

bootstrap(HeroesListComponent, [HeroesService, RestoreService, OtherService])

fixes the error.

I didn't fully investigate your example but you have RestoreService and OtherService added to providers: in hero-editor.components.ts, which makes them known there but it doesn't make them known to the whole application.

Note: If you want to have only one instance of the service in your application (singleton) only add it on one place - usually bootstrap(...). If you want DI to create a new instance for each component, add it to the components providers.

like image 166
Günter Zöchbauer Avatar answered Feb 18 '26 13:02

Günter Zöchbauer