This article will demonstrate built-in AngularJS Services as well as how you can create your own custom service in an AngularJS. This article begins with a brief introduction to AngularJS Services. Afterwards, it demonstrates built-in AngularJS Service with syntax and links to an example on Plunker Editor. Finally, the article discusses custom AngularJS Services.
AngularJS Services AngularJS Services are re-usable components or the objects, which have the methods and the properties to perform some business logic and can be used throughout your Application. To use an AngularJS Service in controller, filter, Service and Directive; just add it as a dependency. Angular comes with some built-in Services but you can create your own custom Service as well.
Built-in AngularJS Service
AngularJS built-in services always start with a $ sign. Some of the commonly used built-in Services are shown below.
- $http
- $resource
- $q
- $anchorSrcoll
- $cacheFactory
- $locale
- $timeout
- $cookies
- $routeProvider
- $routeParams
- $log
$http
This Service is used to communicate with the Servers over the network; i.e., you can send raw requests like getting and posting the data etc., and to recieve the resposne from the remote Server through this Service.
Syntax
- var app=angular.module('app',[]);
- app.controller('mycontroller',['$http',function($http){
-
-
- $http({
- method: 'GET',
- url: '/someUrl'
-
- }).then(function successCallback(response) {
-
-
- }, function errorCallback(response) {
-
-
- });
-
-
- $http.get('/someUrl').then(function successCallback(response) {
-
-
- }, function errorCallback(response) {
-
-
- });
-
- }]);
$resource
$resource is used for the same purpose as $http Service but the key difference between them is that $resource is based on a RESTful architecture and is used to access Restful Web Services. For using $resource Service, you just need to add Angular-resource script file after AngularJS and dependency of ngResource into Angular module, as shown in the syntax given below.
Syntax
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>//angulrJS file
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-resource.js"></script>//ngresource file
- <script src="your script file"></script>
-
-
- var app=angular.module('app',['ngResource']);
- app.controller('mycontroller',['$resource',function($resource){
-
-
- $resource('/someURL').get().$promise.then(function(data){
-
-
- },function(response){
-
- });
-
- }]);
$q
$q service is used to handle the promises and the deferred objects. Promises are the pending results of the asynchronous calls and deferred objects returns promises and the results of asychronous operation after its completion to the calling code.
How $q works
Step 1
The client sends asynchronous call to the Service.
Step 2
The Service receives the call and create a deferred object by using $q Service.
Step 3
The deferred object returns the promise to the client.
Step 4The client uses this promise to write callback functions.
Step 5The Service performs the work and return the status of the function, which is either successfully completed or rejected through deffered object to the client.
Step 6The client executes success or an error callback function, which is based on the result return from the Service.
Syntax
- var myApp = angular.module('myApp', []);
-
-
- myApp.service('myService',['$q',function($q) {
-
-
- var defferedObject = $q.defer();
-
-
- defferedObject.notify('notification messages');
-
-
-
- defferedObject.reject('Error Message');
-
-
-
-
- defferedObject.resolve(data);
-
-
- return defferedObject.promise;
-
- }]);
-
- myApp.controller('myController',['myService',function(myService){
-
-
-
- myFunction().then(successCallBack, errorCallBack, notificationCallBack);
-
- function successCallBack(data) {
-
- }
-
- function errorCallBack(error) {
-
- }
-
- function notificationCallBack(notification) {
-
- }
- }]);
Plunker- $q Service Example
$anchorScroll
$anchorScroll service is used to navigate or scroll within the page.
Syntax
- var myApp=angular.module('myApp', [])
- myApp.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
- function($scope, $location, $anchorScroll) {
- $scope.gotoBottom = function() {
-
-
- $location.hash('bottom');
-
-
- $anchorScroll();
- };
- }]);
$cacheFactory
$cacheFactory Service is used to cache the data. This Service provides functions through which you can define the capacity of the data objects or the items to be cached, get cache information, put and get the data from cache.
Syntax
- var myApp=angular.module('myApp', []);
- myApp.controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
-
- $scope.cache = $cacheFactory('cacheId',{capacity:3});
-
-
- $scope.cache.put(key,value);
-
- $scope.cache.get(key);
-
- $scope.cache.info();
-
- }]);
$locale
$locale Service is used for localization, which is based on the date and numeric formatting. Go to the URL
https://code.angularjs.org/1.5.6/i18n/, choose the localization file and add it to your project.
Syntax
- var myApp = angular.module('myApp', []);
- myApp.controller('localeController', ['$scope','$locale', function($scope,$locale) {
-
-
- $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;
-
- $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;
- }]);
Plunker- $locale Example
$timeout
$timeout Service evaluates some expression or calls a function after some delay. It takes two parameters, where one is the function which is to be called and second is the amount of delay in miliseconds before executing the function.
Syntax
- var myApp = angular.module('myApp', []);
- myApp.controller('timeoutController', ['$scope', '$timeout', function($scope, $timeout) {
-
- $timeout(function() {
- //do some stuff
- }, 5000);
-
- }]);
$cookies
$cookies Service provides an access to the Browser cookies. You can keep the data and get the data fom the Browser cookies. For using $cookies Service, you just need to add Angular-cookies script file after AngularJS and dependency of ngCookies into Angular module, as shown below.
Syntax
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular-cookies.js"></script>
- <script src="your script file"></script>
-
- var myApp=angular.module('myApp', ['ngCookies'])
- .controller('cookiesController', ['$cookies', function($cookies) {
-
-
- var myCookie = $cookies.get('myCookieName');
-
-
- $cookies.put('myCookieName', 'cookie Value');
-
- $cookies.remove('myCookieName');
-
- }]);
$routeProvider$routeProvider Service is used to configure the routes or the URLs for your Application. In order to configure routes, $routeProvide is injected in config function of an Angular module. You also need to add Angular-route script file after AngularJS and dependency of ngRoute into an Angular module, as shown below.
Syntax
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>//angularJS file
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>//angular-route file
- <script src="your script file"></script>
-
- angular.module('myApp', ['ngRoute']).config(function($routeProvider) {
-
- $routeProvider
- .when('/someUrl', {
- templateUrl: 'templateURL(/abc.html)',
- controller: 'ControllerName'
-
- })
- .otherwise('/someURL');
-
-
- });
Plunker-$routeProvider Exampe
$routeParams
$routeParams Service is used to retrieve the values of the parameters, which are passed in URL's. While configuring a route, you can specify the parameters in the URL segment by using colon followed by a parameter name.
Synatx
- angular.module('myApp', ['ngRoute']).config(function($routeProvider) {
-
- $routeProvider
-
- .when('/someUrl/:parameterName', {
- templateUrl: 'templateURL(/abc.html)',
- controller: 'ControllerName'
-
- })
- .otherwise('/someURL');
-
- })
- .controller('myController', function($scope,$routeParams) {
-
- $scopr.value=$routeParams.parameterName;
-
- });
Plunker-$routeParams Example $log
$log service is used for debugging and troubleshooting purpose.
Synatx
- angular.module('myApp', [])
- .controller('myController', ['$scope', '$log', function($scope, $log) {
-
- $log.log("log")
- $log.warn("log warn")
- $log.info("log info")
- $log.error("log error")
- $log.debug("log debug")
- }]);
Custom AngularJS Services
There are five different ways through which you can create custom Services in AngularJS.
- provider()
- factory()
- service()
- value()
- constant()
provider()
This type of Service is created at the configuration phase.The provider function takes two parameters, the name of Service and the function. The function must contain $get property and the value of this proerty is a function, which is used to create a Service.
Syantax
- var myApp=angular.module('myApp',[]);
-
- myApp.config(function($provide){
-
- $provide.provider('serviceName',function(){
-
- this.$get=function(){
- return{
-
- }
- };
-
- });
-
- });
$provide Service is used to create injectable Services.
facory()
The factory function takes two parameters, the name of the Service and the function, which creates and returns Service.
Synatx
service()
The method to create Service through Service() function is same as factory() function but the main difference between them is that Angular treats the function, which is passed to the Service() as a constructor and executes it with the new operator.
Syntax
- var myApp=angular.module('myCustomServiceModule', []);
-
- myApp.service('myService', [function() {
-
- return {
-
- };
- }]);
value()
This fucntion is the short version of factory(). The value function can be used in place of factory, if you dont want to inject anything in your Service.
Syntax
constant()
The constant funcion is used to define constant values for your Application. This function takes two parameters, the name of the Service and an object literal, which represents the Service.
Syntax
- var myApp=angular.module('myApp',[]);
-
- myApp.constant('appSettings',{
- APP_NAME:"Constant Demo App"
-
- });
Summary
In this article, I discussed some of the commonly used built-in AngularJS Services and the methods through which you can create Custom Services in AngularJS.