Types of AngularJS Services with Examples – Creating/Registering Services

Earlier we talked about Filters in AngularJS. In this article, we will discuss what is AngularJS Services with its types: built-in and custom services. Along with this, we will learn how to create and register services in AngularJS with an example.

AngularJs service is a function, which can use for the business layer of an application.

What are Angular Services

What is AngularJS Services?

AngularJs service is a function, which can use for the business layer of an application. It is like a constructor function that will invoke only once at runtime with new. Services in AngularJS are stateless and singleton objects because we get only one object in it regardless of which application interface created it.

We can use it to provide functionality in our web application. Each service performs a specific task.

When to use Services in AngularJS?

We can use AngularJS services when we want to create things that act as an application interface. It can be used for all those purposes for which constructor is used.

Types of AngularJS Services

There are two types of services in angular:

  1. Built-in services – There are approximately 30 built-in services in angular.
  2. Custom services – In angular if the user wants to create its own service he/she can do so.

Do you know What are AngularJS Events and list of HTML Event Directives?

Built-in Services in AngularJS

They are pre-built services in AngularJS. These services get registered automatically at runtime with the dependency injector. Therefore, by using dependency injector we can easily incorporate these built-in services in our angular application.

The various built-in services are as follows:

i. $http

It is a service to communicate with a remote server. It makes an ajax call to the server.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="demoApp" ng-controller="myController">

<p>Today's welcome message is:</p>

<h1>{{message}}</h1>

</div>

<p>A page is requested on server by $http, and the response is set as the value of the "message" variable.</p>

<script>
var httpmodule = angular.module('demoApp', []);
httpmodule.controller('myController', function($scope, $http) {
  $http.get("demo.htm").then(function (response) {
     $scope.message = response.data;
    });
  });
</script>

</body>
</html>

Output:

Message is:

Hello AngularJS Students

A page is requested on a server by $http, and the response is set as the value of the “message” variable.

Recommended Reading – How MVC Works in AngularJS?

ii. $interval

It is a wrapper in angular for window.setInterval.

<!DOCTYPE html>
<html ng-app="intrApp">

<head>
  <meta charset="utf-8" />
  <title>$interval angularjs</title>
  <script src="https://code.angularjs.org/1.3.15/angular.js">          
  </script>
  <script src="script.js"></script>
  </head>

  <body ng-controller="IntervalController">

    <br /><br />The value of counter is: {{cnt}}
  </body>
  <script>
   var sample = angular.module("intrApp", []);

    sample.controller("IntervalController", function($scope, $interval) {


      $scope.cnt = 0;

      $scope.increment = function() {
        $scope.cnt += 1;
};


      $interval(function() {
        $scope.increment();
      }, 2000);

      });
    </script>
</html>

Output:

The value of the counter is: 0

But the value gets increased by 1 in every 2milisecond.

iii. $timeout

It is the same as setTimeout function in javascript. To set a time delay on the execution of a function $timeout is used.

<!DOCTYPE html>
<html ng-app="myApp">

<head>
   <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
   <script src="script.js"></script>
  </head>
   <body ng-controller="timeController">
    <div>
      <div>Message is displayed afer 3 seconds : {{msg}}</div>
   </div>
   <script>
var sample = angular.module('myApp', []);
sample.controller('timeController', function($scope, $timeout) {
   $timeout( function(){
      $scope.msg = "Hey!";
    }, 3000 ); 
 });

   </script>
   </body>
</html>

Output:

The message is displayed after 3 seconds: Hey!

iv. $anchorscroll 

The page which specifies by an anchor in $location.hash() scrolls using $anchorscroll.

v. $animate 

It consists of many DOM (Document Object Model) utility methods that provide support for animation hooks.

Also, see Major Directives for AngularJS HTML DOM

vi. $animateCss

It will perform animation only when ngAnimate includes, by default.

vii. $cacheFactory 

It is a factory that constructs cache objects. It puts the key-value pair and retrieves the key-value pair. Also, it can provide access to other services.

viii. $templateCache 

Whenever a template is used for the first time, it is loaded in template cache. It helps in quick retrieval.

ix. $compile

We can compile HTML string or DOM in the template by it. Also, it produces a template function which will use to link template and scope together.

x. $controller

By using a $controller, we can instantiate Angular controller components.

xi. $document

J-query wrapped the reference to the window. Document element is specified by it.

xii. $exceptionHandler

Any uncaught exception in an angular expression is sent to this service.

xiii. $filter

Use to format the data for displaying to the user.

xiv. $httpParamSerializer

It converts an object to a string.

xv. $httpParamSerializerJQLike

We can sort Params in alphabetic order. It follows j-query’s param() method logic.

xvi. $xhrFactory

XMLHttpRequest objects is created using factory function.

xvii. $httpBackend

Browser incompatibilities can be handled using it.

xviii. $inerpolate

Use for data binding by HTML $compile service.

Let’s revise 2 Different types of Data Binding in AngularJS

xix. $locale

For various angular components, localization rules can be provided using $locale.

xx. $location

URL in the address bar of a browser is parsed by it and then the URL is made available to your application. Changes to the URL in the address bar is reflected in $location service and vice-versa.

xxi. $log

It is a console logger.

xxii. $parse

Use to convert Angular expression into a function using $parse.

xxiii. $q

A function can run asynchronously using $q and its return value, which will use when they finish the processing.

xxiv. $rootElement

It is a root element of the angular application.

xxv. $rootScope

Use in an angular application.

xxvi. $sceDelegate 

Use in the backend by $sce.

Customs Services in AngularJS

We can create our own service by connecting it with a module in AngularJS. And to use it add it as a dependency while defining controller.

Here, in the below code we created a custom service demo.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>The octal value of 225 is:</p>
</div>
<p>A custom service with a method that converts a given number into a octal number.</p>
<script>
var app = angular.module('myApp', []);

app.service('demo', function() {
  this.myFunc = function (x) {
     return x.toString(8);
   }
});
app.controller('myCtrl', function($scope, demo) {
   $scope.hex = demo.myFunc(225);
});
</script>

</body>
</html>

Output:

The octal value of 225 is:

377

A custom service with a method that converts a given number into an octal number.

How to Create and Register AngularJS Services?

We can create angular services by registering it into a module. The module operates services.

In angular JS, there are three ways to create service in AngularJS.

Three Ways to create services in AngularJS

1. Factory

Using Modules factory API, we can create service. We can use a factory method to create an object, properties add to it and return the same object.

Have a Look at 8 Types of Global API’s with examples

Syntax:

var sample = angular.module("app", []);

sample.factory('factoryName',function(){
     return factoryObj;
   });

2. Service

We can use a new keyword to instantiate it, an instance of the function will pass by service. The instance of an object is the service object. Angular JS registers service object. Here, we can inject this object into various other components of angular application such as controller, directives, services, filters etc.

Syntax:

var sample = angular.module("app", []);
sample.service('serviceName',function(){ });

3. Provider

We can pass only $provider into the .config function. It uses $get function to return value. It will use before making a service available you want to provide module –wise configuration for the service object.

Syntax:

var sample = angular.module("app", []);
// syntax to create a provider
sample.provider('providerName',function(){ });
//syntax to configure a provider
sample.config(function(providerNameProvider){});

AngularJS Service v/s Factory

Service and factory both are singletons.

AngularJS .Service is like a constructor while .factory is a method that returns a value.

AngularJS .factory() provides us much more power and flexibility, whereas a .service() is the “end result” of a .factory() call.

Angular Services Example

<!Doctype HTML>
<html>
<head>
   <title>AngularJS Services Tutorial</title>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
   <script src="main.js"></script>
</head>
<body>
<div>
   <div ng-app="mainApp" ng-controller="myController">
      <p><b>Message From Service: </b>{{serviceMsg}}</p>
      <p><b>Message From Factory: </b>{{factoryMsg}}</p>
      <p><b>Message From Provider:</b>{{providerMsg}}</p>
   </div>
</div>
<script>
var sample = angular.module('mainApp', []);

//define a service named myService
sample.service('myService', function () {
   this.message = '';
   this.setMessage = function (newMsg) {
      this.msg = newMsg;
      return this.msg;
   };
});

//define factory named 'myFactory'
sample.factory('myFactory', function () {
   var obj = {};
   obj.message = '';
   obj.setMessage = function (newMsg) {
      obj.message = newMsg;
   };
  return obj;
});

//Defining a provider 'configurable'
sample.provider('configurable', function () {
   var returnMessage = '';
   this.setMessage = function (newMsg) {
      returnMessage = newMsg;
   };
   this.$get = function () {
      return {
         message: returnMessage
      };
   };
});
//configuring provider
sample.config(function (configurableProvider) {
   configurableProvider.setMessage("Hello, This is Provider here!");
});

//defining controller
sample.controller('myController', function ($scope, myService, myFactory, configurable) {
   $scope.serviceMsg = myService.setMessage("Hello,This is Service here!");

   myFactory.setMessage("Hello,This is Factory here! ");
   $scope.factoryMsg = myFactory.message;

   $scope.providerMsg= configurable.message;
});
</script>
</body>

</html>

Output:

A message From Service: Hello, This is Service here!

Message From Factory: Hello, This is Factory here!

Message From Provider: Hello, This is Provider here!

Dependencies in Servies

Like you declare dependencies in a controller, similarly, you can declare dependencies in AngularJS services too. We can declare the dependency in service by specifying them in a factory function signature of service.

var batch = angular.module('batchModule', []);
batch.factory('batchLog', ['$interval', '$log', function($interval, $log) {
 var msgQueue = [];

 function log() {
  if (msgQueue.length) {
    $log.log('batchLog messages: ', msgQueue);
    msgQueue = [];
   }
  }
  $interval(log, 50000);

  return function(message) {
    msgQueue.push(message);
}
}]);
batch.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope',
 function($route, batchLog, $rootScope) {
  return {
   startMonitoring: function() {
    $rootScope.$on('$routeChangeSuccess', function() {
      batchLog($route.current ? $route.current.template : null);
     });
   }
  };
}]);

Summary

Hence from the above article, we can conclude that AngularJS services are a chunk of code can re-use to perform a specific task. There are a number of services provided by angular for various tasks and you can create your own services too. You may also, like AngularJS Dependency Injection Tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.