AngularJS Services ( built-in and custom )

As we learned in angular introduction, services are stateless and singleton objects that provide functionality for a web application. For example, $http is a core service for making HTTP calls to web servers. In simple terms, you can assume angular services as a chunk of reusable code that performs one or more related tasks (e.g. Utility classes with static methods in Java). In AngularJS, there are several built-in services – and you can create your own custom services as well.

Table of Contents

Built-in Services
Creating Custom Services
How to use Services

Built-in Angular Services

As mentioned earlier, angular provides several built-in services which can be used on the fly. In runtime, these services are automatically registered with the dependency injector, so you can easily incorporate them into your angular applications by using dependency injection. e.g. to use $http service in a controller, inject the service as below:

module.controller('DemoController', function( $http ){
    //...
});

Let’s list down angular built-in services.

Service Name Description
$anchorScroll Provides capability to scroll to page anchor specified in $location.hash()
$animate This service exposes a series of DOM utility methods that provide support for animation hooks.
$animateCss By default, only when the ngAnimate is included, then this service will perform animations.
$cacheFactory Factory that constructs Cache objects, put and retrieve key-value pairs and give it’s access to other services.
$templateCache The first time a template is used, it is loaded in the template cache for quick retrieval.
$compile Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.
$controller This is responsible for instantiating angular controller components.
$document Specifies a jQuery-wrapped reference to window.document element.
$exceptionHandler Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.
$filter Filters are used for formatting data displayed to the user.
$httpParamSerializer Default $http params serializer that converts object to string.
$httpParamSerializerJQLike Alternative $http params serializer that follows jQuery’s param() method logic. The serializer will also sort the params alphabetically.
$http This service facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP.
$xhrFactory Factory function used to create XMLHttpRequest objects.
$httpBackend Used for dealing with browser incompatibilities.
$interpolate Compiles a string with markup into an interpolation function. This service is used by the HTML $compile service for data binding.
$interval Angular’s wrapper for window.setInterval.
$locale Provides localization rules for various Angular components.
$location It parses the URL in the browser address bar and makes the URL available to your application. Changes to the URL in the address bar are reflected into $location service and changes to $location are reflected into the browser address bar.
$log Console logger.
$parse Converts Angular expression into a function.
$q Helps you run functions asynchronously, and use their return values (or errors) when they are done processing.
$rootElement The root element of Angular application.
$rootScope Scopes provide separation between the model and the view. This is for root scope. Every application has a single root scope.
$sceDelegate Used by the $sce in backend.
$sce provides Strict Contextual Escaping services to AngularJS.
$templateRequest It runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache.
$timeout Angular’s wrapper for window.setTimeout()
$window A reference to the browser’s window object. While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

Reference: https://docs.angularjs.org/api/ng/service

Creating Custom Angular Services

Placing application’s business logic and common operations in a single place, is always a good design. This improves code re-usability and avoid code duplication. You should put all such logic in custom angular services. This makes code modular and more maintainable.

Further, your code becomes more testable. Remember, angular provides first class support for unit testing. Thus we can quickly write tests for these services and avoid many possible defects.

There are mainly two ways to declare angularjs services. Let’s understand both ways:

Using – module.service( ‘serviceName’, function(){} )

When you create a service using module.service(), an instance of the function() passed as second parameter becomes the service object that AngularJS registers and injects later to other services / controllers when asked for.

The syntax for declaring methods in custom service object using module.service() is :

module.service('DemoService', function() {
	//"this" will be used as service instance
    this.firstMethod = function() {
        //..
    }
 
    this.someOtherMethod = function() {
        //..
    }
});

Using – module.factory( ‘factoryName’, function(){} )

When you create a service using module.factory(), return value of function() passed as second parameter becomes the service object that AngularJS registers and injects later to other services / controllers when asked for.

The syntax for declaring methods in custom service object using module.factory() is :

module.factory('DemoService', function() {
	//"factory" will be used as service instance
	var factory = {}; 

    factory.firstMethod = function() {
        //..
    }
 
    factory.someOtherMethod = function() {
        //..
    }

    return factory;
});

How to use AngularJS Services

This example demonstrate the use of a custom service which has logic for displaying current time in different timezones. Let’s first create the custom service.

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

//Create a function
function TimeObj() {
    var cities = {
        'Los Angeles': -8,
        'New York': -5,
        'London': 0
    };
    this.getTZDate = function(city) {
        var localDate = new Date();
        var utcTime = localDate.getTime() + localDate.getTimezoneOffset() * 60 * 1000;
        return new Date(utcTime + (60 * 60 * 1000 * cities[city]));
    };
    this.getCities = function() {
        var cList = [];
        for (var key in cities) {
            cList.push(key);
        }
        return cList;
    };
}

//Register as service 'TimeService'
app.service('TimeService', [TimeObj]);

Now to use this service, use controllers like below:

app.controller('LAController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("Los Angeles").toLocaleTimeString();
    }
]);

app.controller('NYController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("New York").toLocaleTimeString();
    }
]);

app.controller('LondonController', ['$scope', 'TimeService',
    function($scope, timeS) {
        $scope.myTime = timeS.getTZDate("London").toLocaleTimeString();
    }
]);

Now you can use controllers in your webpage to dispaly different times.

<html ng-app="myApp">
	<head>
		<title>AngularJS Custom Time Service</title>
		<style>
			span {
				color: lightgreen; background-color: black;
				border: 3px ridge; padding: 2px;
				font: 14px/18px arial, serif; 
			}
		</style>
	</head>
	<body>
		<h2>Custom Time Service:</h2><hr>

		<div ng-controller="LAController">
		Los Angeles Time:
		<span>{{myTime}}</span>
		</div><hr>

		<div ng-controller="NYController">
		New York Time:
		<span>{{myTime}}</span>
		</div><hr>

		<div ng-controller="LondonController">
		London Time:
		<span>{{myTime}}</span>
		</div>

	</body>
</html>

The output will look like this:

See the Pen Angular Service Demo – Timezone Example by Lokesh (@howtodoinjava) on CodePen.

That’s all for this introductory AngularJS Services tutorial. Drop me your questions in comments section.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial