AngularJS Service and Factory

Updated on     Kisan Patel

Services provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner.

Services are singleton objects that are instantiated only once per app and lazy-loaded (created only when necessary). They provide an interface to keep together those methods that relate to a specific function.

For example, the built-in $timeout service executes a function after a specified interval. The $http service encapsulates the logic required to interact with REST api. We ask AngularJS to inject these services into our controllers so that we can utilize them.

angular.module('myApp').controller('TestController',
   function($http,$timeout){
       //use $http, $timeout here
});

In the above code, TestController declares dependency on two services: $http and $timeout. So, when the controller is instantiated, AngularJS passes the two services to it.

Similarly, you can create your own services that encapsulate the business logic specific to your apps. Here is how you register a service in a module:

angular.module('myModule', [])
    .service('helloWorldService', function(){
        this.hello = function() {
            return "Hello World";
        };
    });

In above code, angular.module() provides a function service() that’s used to register a service. The first argument to this function is the service name. The second argument is a constructor function.

A factory is another injectable type. Effectively it’s the same as a service. The difference between service and factory are, with the factory you actually create an object inside of the factory and return it but with the service you just have a standard function that uses the this keyword to define function.

The most common and flexible way to create a service uses the angular.module API factory:

angular.module('myModule', [])
     .factory('ServiceName', function() {
            var serviceInstance = {};
            // Our first service
            return serviceInstance;
    });

Here’s an example of a service and a factory that accomplish the same thing.

var app = angular.module('app',[]);

app.service('helloWorldService', function(){
    this.hello = function() {
        return "Hello World";
    };
});

app.factory('helloWorldFactory', function(){
    return {
        hello: function() {
            return "Hello World";
        }
    }
});

Now, lets utilise a Service to implement your business logic and use dependency injection to use this service in our controllers.

<div ng-app="app" ng-controller="MyController">
   <ul ng-repeat="user in users">
      <li>{{ user }}</li>
   </ul>
   <div ng-controller="AnotherController">
      First user: {{ firstUser }}
   </div>
</div>
<script type="text/javascript">
var myApp = angular.module('app', []);

myApp.factory("UserService", function() {
    var users = ["Kisan", "Devang", "Ravi", "Ujas", "Sanket"];
 
    return {
       all: function() {
            return users;
       },
       first: function() {
            return users[0];
       }
    };
});

myApp.controller("MyController", function($scope, UserService) {
    $scope.users = UserService.all();
});

myApp.controller("AnotherController", function($scope, UserService) {
    $scope.firstUser = UserService.first();
});
</script>

The factory method creates a singleton UserService, that returns two functions for retrieving all users and the first user only. The controllers get the UserService injected by adding it to the controller function as params.

angulajs-services-demo

 


AngularJS

Leave a Reply