Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsure about the best approach for retrieving the returned value from the Service in the calling Controller.
The method I currently use is as follows:
- The Controller initiates the call to the Service
- The Service executes the $http request and checks the promise.
- If the promise is successful, the Service sends out an event with the returned object.
- The Controller listens for that event and performs necessary operations.
While this method works well and allows me to reuse the same event for different requests (e.g. displaying new messages after fetching all messages or posting a message), I have recently decided to implement testing procedures in my application.
When conducting unit tests on my Controllers, I aim to mock certain Services to return specific values. However, since my Services trigger events rather than returning values directly, I anticipate challenges in checking the "return" values of the Services during testing.
Therefore, I am seeking opinions on whether I may have overlooked something in my approach. Is it advisable to retrieve promises directly into Controllers when invoking Services? Would this be a more effective or efficient way to handle such scenarios?
While I understand that each application has its unique logic, I believe that in AngularJS, adhering to specific set of choices and best practices is crucial for maintaining modularity and testability.
Any suggestions or insights would be greatly appreciated.