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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With