I\'ve built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three o
You get this error if you have service A that depends on a static property / method of service B and the service B itself depends on service A trough dependency injection. So it's a kind of a circular dependency, although it isn't since the property / method is static. Probably a bug that occurs in combination with AOT.
Well for me the issue was even more annoying, I was using a service within a service and forgot to add it as dependency in the appModule! Hope this helps someone save several hours breaking the app down only to build it back up again
You have to add providers array in @Component decorator or in the module where your component is declared. Inside component you can do as below:
@Component({
moduleId: module.id,
selector: 'pm-header',
templateUrl: 'header.component.html',
styleUrls: ['header.component.css'],
directives: [ROUTER_DIRECTIVES, NgClass],
providers: [MobileService]
})
If your service is defined in the same file as a component (that consumes it) and the service is defined after the component in the file you may get this error. This is due to the same 'forwardRef' issue others have mentioned. At this time VSCode isn't great about showing you this error and the build compiles successfully.
Running the build with --aot
can mask this problem due to the way the compiler works (probably related to tree shaking).
Solution: Make sure the service is defined in another file or before the component definition. (I'm not sure if forwardRef can be used in this case, but it seems clumsy to do so).
If I have a very simple service that is very strongly tied to a component (sort of like a view model) - eg. ImageCarouselComponent
, I may name it ImageCarouselComponent.service.ts
so it doesn't get all mixed up with my other services.
I have encountered this error by mistyping the service's name, i.e. constructor (private myService: MyService).
For misspelled services, I was able to determine which service was the problem (I had several listed in the constructor) by inspecting the page in Chrome->Console. You will see as part of the message a "parameter" array list by displaying object Object, object Object, ? (or something like that). Notice where the "?" is and that is the position of the service that is causing the problem.
I also encountered this by injecting service A into service B and vice versa.
I think it's a good thing that this fails fast as it should probably be avoided anyway. If you want your services to be more modular and re-usable, it's best to avoid circular references as much as possible. This post highlights the pitfalls surrounding that.
Therefore, I have the following recommendations:
EventService
) which both services can inject in order to exchange messages.