AngularJS > Components

Services in AngularJS

What are Services in AngularJS?


AngularJS services are functions or objects that hold behavior or state that can be used across the application (entire web page). Each AngularJS service is instantiated only once because of singleton in nature.

These services area lazy loaded (instantiated only when it is called for the first time) and singleton in nature (only one instance of the object is available throughout the application).

All services in AngularJS starts with "$" and here are some inbuilt AngularJS services

  • $window - to work with the JavaScript window object.
  • $location - it helps us to interact with URL in the browser. This has following function
    • absUrl - gets absolute URL of the browser
    • url - gets and sets URL, pass url to set otherwise gets the current url
    • path - gets and sets the path of the url
    • search - gets or sets the querystring of the current url
  • $http - used to make GET or SET Ajax call to the server and deal with server responses and errors.

Apart from using inbuilt AngularJS services, we can also create our own service. A custom service can use any of the existing inbuilt or custom services. Below can be the best scenarios where a service is created

  • If we need to create reusable code
  • Application level state of the object
  • Integration of third party services
  • Caching 

Sample service application

    <div ng-app="myApp">
        <div ng-controller="myController">
            a = <input type="number" required ng-model="a" value="5" />
            b = <input type="number" required ng-model="b" value="7" />
            <button ng-click="Plus()">Add</button>
            <button ng-click="Minus()">Subtract</button>
            <p>The result is: <b>{{MathResult}}</b></p>
        </div>
    </div>

    <script>
        var myApp = angular.module('myApp', [])
// create service
        myApp.service('myService', function () {
            this.Sum = function (a, b) {
                return a + b;
            };
            this.Subtract = function (a, b) {
                return a - b;
            };
        });

        myApp.controller('myController', function ($scope, myService) {
            
            $scope.Plus = function () {
                $scope.MathResult = myService.Sum($scope.a, $scope.b);
            };

            $scope.Minus = function () {
                $scope.MathResult = myService.Subtract($scope.a, $scope.b);
            };
        });
    </script>

In the above code snippet, we have two textboxes and a button. On click of Add button, we are calling Plus() function and on click of Subtract button, we care calling Minus() function. Both are being triggered using AngularJS ng-click directive so that AngularJS function is callled not the normal JavaScript function.

The result placeholder is {{MathResult}}.

In the script block, we have created a module 'myApp' and then created a service 'myService'. In that service, we have created two functions Sum and Subtract.

In the 'myController', those function, along with the $scope, myService is also being called. In Plus() and Minus() function, Sum() and Subtract() function of the myService is being called and the result is set to MathResult.

Another way to declare a service in AngularJS

Instead of using .service() method, we can also use .factory() method to create an injectable object and expose these functions.

      // create service  
myApp.factory('myService', function () {
            var thisService = {};
            thisService.Sum = function (a, b) {
                return a + b;
            }
            thisService.Subtract = function (a, b) {
                return a - b;
            }
            return thisService;
        });

In the above code snippet, we have used .factory() method and passed the 1st parameter as the service name and the 2nd parameter is the actual service definition. In this service, we have created the thisService object and defining Sum and Subtract function on it.

 Views: 4355 | Post Order: 12




Write for us