× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Angular services and single responsibility principle

Alexey Naumov
May 25, 2016
<p>Each part of our code has to have his own responsibility. Like anything else in our live. For example we have a phone and it responsible for calls, chats etc. We don't ask phone to clean teeths or cook dinner. Same thing for each class in a project. One class - one task. </p> <p>Check out wiki about that https://en.wikipedia.org/wiki/Single_responsibility_principle</p> <p>That's why we extract logic from controller into services. We want to make sure, that controllers only bind user interaction from UI to services and does not contain business logic.</p> <p>angular guide:</p> <p>https://docs.angularjs.org/guide/services</p> <p>https://docs.angularjs.org/guide/providers - general case (providers)</p> <p> </p> <p>Further I'll show you typical examples of code, which can be moved from controller to service:</p> <p> - API call (everything with $http service)</p> <p> - share data between controllers (share data with $rootScope isn't good idea)</p> <p> - big methods (chunks of code over 20 lines can be moved into separate service)</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus