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 (by the $injector ) and lazy-
loaded (created only when necessary). They provide an interface to keep together those methods
that relate to a specific function.
Angular comes with several built-in services with which we’ll interact consistently. It will also be
useful to make our own services for any decently complex application.
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. |
Using 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>
$log Service
AngularJs includes logging service $log, which logs the messages to the browser’s console.
The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.
Example: $log
<!DOCTYPE html>
<html>
<head>
<script src=”~/Scripts/angular.js”></script>
</head>
<body ng-app=”myApp” >
<div ng-controller=”myController”>
<p>Please check the browser console for the logging information.</p>
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($log) {
$log.log(‘This is log.’);
$log.error(‘This is error.’);
$log.info(‘This is info.’);
$log.warn(‘This is warning.’);
$log.debug(‘This is debugging.’);
});
</script>
</body>
</html>
$http Service
The $http service is used to send or receive data from the remote server using browser’s XMLHttpRequest or JSONP. $http is a service as an object. It includes following shortcut methods.
Method | Description |
$http.get() | Perform Http GET request. |
$http.head() | Perform Http HEAD request. |
$http.post() | Perform Http POST request. |
$http.put() | Perform Http PUT request. |
$http.delete() | Perform Http DELETE request. |
$http.jsonp() | Perform Http JSONP request. |
$http.patch() | Perform Http PATCH request. |
Let’s look at some of the important methods of $http.
$http.get(): $http.get() method sends http GET request to the remote server and retrieves the data.
Syntax: HttpPromise $http.get(url)
$http.get() method returns HttpPromise object, which includes various methods to process the response of http GET request.
The following example demonstrates the use of $http service in a controller to send HTTP GET request.
Example: $http.get()
<!DOCTYPE html>
<html>
<head>
<script src=”~/Scripts/angular.js”></script>
</head>
<body ng-app =”myApp”>
<div>
<div ng-controller=”myController”>
Response Data: {{data}} <br />
Error: {{error}}
</div>
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get(“/demo/getdata”);
promise.success(onSuccess);
promise.error(onError);
});
</script>
</body>
</html>
In the above example, ‘myController’ controller includes $http parameter, so that it can be used to send GET request. AngularJS automatically injects $scope parameter at runtime. The $http.get() method returns HttpPromise which includes methods like success() and error(). The success() method registers a callback method which is called when a request completes successfully. The error() method registers a callback method which is called when a request fails and returns an error.
The onSuccess() method above, attaches the response data to the $scope. The onError() method attaches status property to the $scope. These methods can be called in chain, as shown below.
Example: $http.get()
<!DOCTYPE html>
<html>
<head>
<script src=”~/Scripts/angular.js”></script>
</head>
<body ng-app =”myApp”>
<div>
<div ng-controller=”myController”>
Response Data: {{data}} <br />
Error: {{error}}
</div>
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get(“/demo/getdata”).success(onSuccess).error(onError);
});
</script>
</body>
</html>
$http.post: The $http.post() method sends Http POST request to the remote server to submit and retrieve the data.
Syntax: HttpPromise $http.post(url, dataToSubmit);
The following example demonstrates $http.post() method.
Example: $http.post()
<!DOCTYPE html>
<html >
<head>
<script src=”~/Scripts/angular.js”></script>
</head>
<body ng-app=”myApp”>
<div ng-controller=”myController”>
Response Data: {{data}} <br />
Error: {{error}}
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
$http.post(‘/demo/submitData’, { myData: ‘Hello World!’ })
.success(onSuccess)
.error(onError);
});
</script>
</body>
</html>
$http(): You can use construction function of $http service to perform http request, as shown below.
Example: $http()
<!DOCTYPE html>
<html >
<head>
<script src=”~/Scripts/angular.js”></script>
</head>
<body ng-app=”myApp”>
<div ng-controller=”myController”>
Response Data: {{data}} <br />
Error: {{error}}
</div>
<script>
var myApp = angular.module(‘myApp’, []);
myApp.controller(“myController”, function ($scope, $http) {
var onSuccess = function (data, status, headers, config) {
$scope.data = data;
};
var onError = function (data, status, headers, config) {
$scope.error = status;
}
var getReq = {
method: ‘GET’,
url: ‘/demo/getdata’
};
$http(getReq).success(onSuccess).error(onError);
var postReq = {
method: ‘POST’,
url: ‘/demo/submitData’,
data: { myData: ‘test data’ }
};
$http(postReq).success(onSuccess).error(onError);
});
</script>
</body>
</html>
Thus, you can use $http service to send AJAX request to the remote server.