I have UserService and MissionService.
Is it ok to inject MissionService in UserSerivce or vice versa?
If yes, what about unit testing?
Yes, the first thing is to add the @Injectable decorator on each services you want to inject. In fact, the Injectable name is a bit insidious. It doesn't mean that the class will be "injectable" but it will decorate so the constructor parameters can be injected.
Angular Service that needs another service You don't have to do much to configure dependency between services. A service that needs another service should have a @Injectable decorator and then you can apply the same constructor injection pattern where you provide the service dependency with in the constructor.
Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.
The @Injectable decorator is not compulsory to add if you don't use the 'providedIn' option. The @Injectable decorator together with the 'providedIn' option means the service should not be added within the providers' array of a module.
Of course you can and it is perfectly fine. But I recommend that you use method-injection in order to allow you to set the instance at runtime without using using reflection (you can create an instance manually).
For example:
@Service public class MissionService { } @Service public class UserService { private MissionService missionService; @Autowired public void setMissionService(MissionService missionService) { this.missionService = missionService; } }
This allows you to create both services using regular Java without Spring:
MissionService missionService = new MissioNService(); UserService userService = new UserService(); userService.setMissionService(missionService);
Caution: You have to take care of not building dependency cycles. It is not set that Spring resolves them, I think
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