Error when trying to inject a service into an angular component “EXCEPTION: Can't resolve all parameters for component”, why?

前端 未结 30 1856
无人共我
无人共我 2020-11-22 17:18

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

30条回答
  •  萌比男神i
    2020-11-22 17:34

    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.

提交回复
热议问题