{"id":14359,"date":"2014-06-29T21:21:45","date_gmt":"2014-06-29T15:51:45","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=14359"},"modified":"2017-08-03T16:00:41","modified_gmt":"2017-08-03T10:30:41","slug":"service-in-angularjs","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/service-in-angularjs\/","title":{"rendered":"Service in AngularJS"},"content":{"rendered":"<p>When we are working on <strong>MVC<\/strong> (or <strong>MVVM<\/strong> for <strong>AngularJS<\/strong>) <strong>Design-Patterns<\/strong>, our application is loosely coupled because of different independent components defined for e.g. <strong>Controller<\/strong>, <strong>View<\/strong>, <strong>Services<\/strong>, <strong>Modal\/Data<\/strong> etc. All the components have their own work\/role but today we will discuss only <strong>Services<\/strong>.<\/p>\n<p><strong>Services<\/strong> are that part of application where we write our business logic and load data (if it is frond-end framework Service e.g. <a title=\"Angular Development\" href=\"http:\/\/www.tothenew.com\/front-end-angularjs-development\">AngularJS Service<\/a> then it loads data from Web Server and if it is back-end framework Service e.g. <strong>NodeJS<\/strong> <strong>Service<\/strong> then it loads data from Database Server or other Web Server). <strong>AngularJS<\/strong> also provides many built-in <strong>services<\/strong> e.g. <strong>$http<\/strong>, <strong>$q<\/strong> etc. <strong>$http<\/strong> is very commonly used <strong>service<\/strong> which helps us to load data from Web Server, we can hit Ajax request with the help of <strong>$http <\/strong><strong>service<\/strong>, which internally hits <strong>XMLHTTPRequest<\/strong>.<\/p>\n<p>Generally, instead of writing <strong>Services<\/strong> we do data loading from Web-Server in <strong>Controllers<\/strong>, which is obviously a bad practice. So lets try a basic program, where we will load data from Web-Server with the help of <strong>Service<\/strong> instead of writing the code into <strong>Controller<\/strong>.<\/p>\n<p>[js]<br \/>\nvar serviceTestApp = angular.module(&#8216;serviceTest&#8217;, []);<\/p>\n<p>\/*<br \/>\n * Defining TestService, Which will load User list Asynchronously(From Web-Server).<br \/>\n * for demo purpose we are using setTimeout().<br \/>\n *<br \/>\n * $q is built-in Angular Service which helps us to implement Promise-Defer Design Pattern and<br \/>\n * will be injected to TestService by AngularJS via DI(Dependency Injection) Design Pattern.<br \/>\n * *\/<br \/>\nserviceTestApp.service(&#8216;TestService&#8217;, function ($q) {<br \/>\n    \/\/ Defining Service function: getUsers which will load user list<br \/>\n    this.getUsers = function () {<br \/>\n        var deferred = $q.defer();<br \/>\n        setTimeout(function () {<br \/>\n            var users = [<br \/>\n                {name: &quot;Amit Thakkar&quot;, age: 25},<br \/>\n                {name: &quot;Namita&quot;, age: 36},<br \/>\n                {name: &quot;Kanika&quot;, age: 43}<br \/>\n            ];<br \/>\n            deferred.resolve(users);<br \/>\n        }, 2000);<br \/>\n        return deferred.promise;<br \/>\n    };<br \/>\n});<br \/>\n[\/js]<\/p>\n<p>Also, <strong>Services<\/strong> must be registered with <strong>module<\/strong>(Same as <strong>directives<\/strong>) via <strong>module.service<\/strong> API, in which first argument is the name of the <strong>Service<\/strong> and second argument is the function. Second argument function is just a constructor function that will be called with <strong>&#8216;new&#8217;<\/strong> keyword by <strong>AngularJS<\/strong> itself. And this <strong>Service<\/strong> will be injected to <strong>Controllers<\/strong> or other <strong>Services<\/strong> (<strong>AngularJS<\/strong> also implement <strong>Dependency Injection<\/strong> Design Pattern to inject <strong>services<\/strong> to <strong>Controllers<\/strong> and <strong>Services<\/strong>).<\/p>\n<p>[js]<br \/>\n\/*<br \/>\n * Defining TestController, who will use TestService to get User List.<br \/>\n * *\/<br \/>\nfunction TestController($scope, TestService) {<br \/>\n    \/\/ Calling getUsers function on TestService.<br \/>\n    TestService.getUsers().<br \/>\n        then(function (users) {<br \/>\n            $scope.users = users;<br \/>\n        });<br \/>\n}<br \/>\n[\/js]<\/p>\n<p><strong>AngularJS<\/strong> <strong>Services<\/strong> implement <strong>Singleton Design Pattern<\/strong> so only one object is created for an application.<\/p>\n<p><strong>NOTE:<\/strong> You can checkout full working source code from this <a href=\"https:\/\/github.com\/AmitThakkar\/AngularDemo\" target=\"_blank\">link<\/a>.<\/p>\n<p><span style=\"font-size: 20px; color: blue;\">Read Further on AngularJS Series<\/span><\/p>\n<ul>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-a-write-less-do-more-javascript-framework\/\">AngularJS :\u00a0A \u201cWrite Less Do More\u201d JavaScript Framework<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-updating-a-label-dynamically-with-user-input\/\">AngularJS :\u00a0Updating a Label Dynamically with User Input<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-adding-items-to-a-javascript-list-and-updating-corresponding-dom-dynamically\/\">AngularJS :\u00a0Adding Items to a JavaScript List and updating corresponding DOM Dynamically<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-text-suggestions\/\">AngularJS :\u00a0Text Suggestions<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-sorting-objects-on-various-attributes\/\">AngularJS :\u00a0Sorting objects on various attributes<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-fetching-data-from-the-server\/\">AngularJS :\u00a0Fetching data from the server<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-multiple-views-layout-template-and-routing\/\">AngularJS :\u00a0Multiple Views, Layout\u00a0Template\u00a0and Routing<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/angularjs-implementing-routes-and-multiple-views\/\">AngularJS :\u00a0Implementing Routes And Multiple Views<\/a><\/li>\n<li><a href=\"http:\/\/www.tothenew.com\/blog\/building-intuitive-frontend-interfaces-with-angularjs\/\">Building Intuitive Frontend Interfaces with AngularJS<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>When we are working on MVC (or MVVM for AngularJS) Design-Patterns, our application is loosely coupled because of different independent components defined for e.g. Controller, View, Services, Modal\/Data etc. All the components have their own work\/role but today we will discuss only Services. Services are that part of application where we write our business logic [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":2},"categories":[1185],"tags":[3955,955,4697,1420,1450,1451,456],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/14359"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=14359"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/14359\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=14359"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=14359"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=14359"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}