Angular Services: Implementation, Examples & Best Practices

AngularJS supports the concept of "Separation of Concerns" using services. Services provide us with a method to keep data across the lifetime of the Angular application. Angular services are substitutable objects that are wired together using dependency injection. We can use services to organize and share code across our app. Services are JavaScript functions that are responsible for specific tasks only. Services provide us with a method to communicate data across the controllers in a consistent way. It provides individual entities that are maintainable and testable. Services are singleton objects and they get instantiated only once per application; controllers and filters only call them on an as-required basis. Services are singleton objects; that means each component dependent on a service gets a reference to the single instance generated by the service factory.

AngularJS provides many inbuilt services like $animate, $http, $route, $window, $location, $compile, $controller, etc.

Let us take some examples of inbuilt services.

$http

AngularJS provides $http control which works as a service to read data from the server. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via the browser’s XMLHttpRequest object or via JSONP.

Example

<html>
<head>
    <title>Angular JS Includes</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Ajax Demo</h2>
    <p ng-app="app" ng-controller="Employee">
        <span>{{Message}}</span><br/>
        <span>{{Status}}</span><br/><br/>
    </p>
    <script>
        var obj = angular.module('app', []);
        obj.controller('Employee', function($scope, $http) {
            $http({
                method: 'GET',
                url: 'index.html'
            }).then(function successCallback(response) {
                $scope.Message = response.data;
                $scope.Status = response.status;
            }, function errorCallback(response) {
                alert("Unsuccessful call!");
            });
        });
    </script>
</body>
</html>

Index.HTML: This is the $Ajax Example.

Output

HTML

$window

$window refers to the browser’s window object. In Angular, we always refer to windows through the $ window service, so it may be overridden or removed for testing.

Example

<html>
<head>
    <title>Angular JS Includes</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body ng-app="app">
    <h2>AngularJS $Window Example</h2>
    <p ng-controller="mycontroller">
        <input type="text" ng-model="message" aria-label="greeting" />
        <button ng-click="doGreeting(message)">ALERT BOX</button>
    </p>
    <script>
        var obj = angular.module('app', []);
        obj.controller('mycontroller', ['$scope', '$window', function($scope, $window) {
            $scope.message = 'I am $window Service!';
            $scope.doGreeting = function(message) {
                $window.alert(message);
            };
        }]);
    </script>
</body>
</html>

Output

AngularJS

$document

The $document is a jQuery wrapper for the browser’s window. object method.

Example

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body ng-app="app">
    <h2>AngularJS $document Example</h2>
    <p ng-controller="myController">
        <span id="pan">Pankaj Kumar Choudhary</span>
        <p>
            <b ng-bind="title"></b>
        </p>
        <p>
            <b ng-bind="windowTitle"></b>
        </p>
    </p>
    <script>
        var obj = angular.module('app', []);
        obj.controller('myController', ['$scope', '$document', function($scope, $document) {
            $scope.title = $document[0].title;
            $scope.windowTitle = angular.element(window.document)[0].title;
        }]);
    </script>
</body>
</html>

Output

Documents

Way to define User Services

Here are the ways to define the services.

  1. factory
  2. service
  3. provider
  4. value

Factory

In the factory method, we first define a factory and then assign a method to it. A factory is a simple function that allows us to add some logic before creating the object and at last we return this object. It is a collection of functions similar to a class. It can be used in multiple controllers with constructor functions.

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>Enter First number: <input type="number" ng-model="number1" /></p>
        <p>Enter Second number: <input type="number" ng-model="number2" /></p>
        <button ng-click="multiply()">Multiply</button>
        <p>Result: {{result}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);

        mainApp.factory('MathService', function() {
            var factory = {};

            factory.multiply = function(a, b) {
                return a * b;
            }

            return factory;
        });

        mainApp.controller('CalcController', function($scope, MathService) {
            $scope.multiply = function() {
                $scope.result = MathService.multiply($scope.number1, $scope.number2);
            }
        });
    </script>
</body>
</html>

Output

Multiply

Service

Using the service method we define a service and after that assign a method to this service. A service is a constructor function that creates the object using a new keyword and we can add function and property to this object using this keyword.

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>

<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>Enter First number:
            <input type="number" ng-model="number1" />
        </p>
        <p>Enter Second number:
            <input type="number" ng-model="number2" />
        </p>
        <button ng-click="multiply()">Multiply</button>
        <p>Result: {{result}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);
        mainApp.service('MathService', function() {
            this.multiply = function(a, b) {
                return a * b;
            }
        });
        mainApp.controller('CalcController', function($scope, MathService) {
            $scope.multiply = function() {
                $scope.result = MathService.multiply($scope.number1, $scope.number2);
            }
        });
    </script>
</body>
</html>

Output

Service

We can also inject an already available service into it. In the below example, we insert a multiply_data method into a service that already exists in factory service.

Example

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>Enter First number:
            <input type="number" ng-model="number1" />
        </p>
        <p>Enter Second number:
            <input type="number" ng-model="number2" />
        </p>
        <button ng-click="multiply()">Multiply</button>
        <p>Result: {{result}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);
        
        mainApp.factory('MathService_Factory', function() {
            var factory = {};
        
            factory.multiply_data = function(a, b) {
                return a * b
            }
            return factory;
        });
        
        mainApp.service('MathService', function(MathService_Factory) {
            this.multiply = function(a, b) {
                return MathService_Factory.multiply_data(a, b);
            }
        });
        
        mainApp.controller('CalcController', function($scope, MathService) {
            $scope.multiply = function() {
                $scope.result = MathService.multiply($scope.number1, $scope.number2);
            }
        });
    </script>
</body>
</html>

Output

Result

Provider

A provider is used to create a configurable service object and the value is returned using the $get() function. We should use the provider method when we need to provide module-wise configuration for your service object before making it available.

Example

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>Multiply of 79 and 13 is</p>
        <p>Result: {{result}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);

        mainApp.provider('configurable', function() {
            var multi = 0;
            this.multiply = function(a, b) {
                multi = a * b;
            };
            this.$get = function() {
                return {
                    data: multi
                };
            };
        });

        mainApp.config(function(configurableProvider) {
            configurableProvider.multiply(79, 13);
        });

        mainApp.controller('CalcController', function($scope, configurable) {
            $scope.result = configurable.data;
        });
    </script>
</body>
</html>

Output

Output

Value

A value service is used to provide a value. It does exactly what we would expect it to and plays a key part in designing flexible, modular Angular applications.

Example

<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>

<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>{{message}}</p>
        <p>Result: {{result}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);
        
        mainApp.value("valueId", 79 * 13);
        mainApp.value("message", "Multiply of 79 and 13 is");
        
        mainApp.controller('CalcController', function($scope, valueId, message) {
            $scope.result = valueId;
            $scope.message = message;
        });
    </script>
</body>
</html>

Output

Example

Example

<!DOCTYPE html>
<html>
<head>
    <title>Angular JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
    <script src="angular.min.js"></script>
</head>
<body>
    <h2>AngularJS Service Example</h2>
    <p ng-app="mainApp" ng-controller="CalcController">
        <p>Enter First number: <input type="number" ng-model="number1" /></p>
        <p>Enter Second number: <input type="number" ng-model="number2" /></p>
        <button ng-click="Result()">Result</button>
        <p>Multiplication: {{multiply}}</p>
        <p>Addition: {{addition}}</p>
        <p>Substraction: {{substraction}}</p>
        <p>pison: {{pison}}</p>
    </p>
    <script>
        var mainApp = angular.module("mainApp", []);

        // Factory
        mainApp.factory('MathService', function() {
            var factory = {};
            factory.multiply = function(a, b) {
                return a * b;
            };
            return factory;
        });

        // Service
        mainApp.service('addition', function() {
            this.add = function(a, b) {
                return a + b;
            };
        });

        // Provider
        mainApp.provider('configurable', function() {
            var sub = 0;
            this.substraction = function(a, b) {
                sub = a * b;
            };
            this.$get = function() {
                return {
                    data: sub
                };
            };
        });

        mainApp.config(function(configurableProvider) {
            configurableProvider.substraction(79, 13);
        });

        // Value
        mainApp.value("valueId", 79 / 13);

        // Controller
        mainApp.controller('CalcController', function($scope, MathService, addition, configurable, valueId) {
            $scope.Result = function() {
                $scope.multiply = MathService.multiply($scope.number1, $scope.number2);
                $scope.addition = addition.add($scope.number1, $scope.number2);
                $scope.substraction = configurable.data;
                $scope.pison = valueId;
            };
        });
    </script>
</body>
</html>

Output

Enter Number

In the above example, we used factory, service, value, and provider services.

Read more articles on AngularJS.


Similar Articles