Introduction to AngularJS Services

If you are interested to learn about the Angular ajax $http

In AngularJS you can make your own service, or use one of the many built-in services. Service in AngularJS is a function or an object that can be used to share data and the behaviour across the application (controller, directives, filters, other services etc.) or we can say services in AngularJS are objects that are wired together using DI (dependency injection) and it can be used to share and organize code across the application.

What is a Service?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service. The $location service has methods which return information about the location of the current web page:

Example

Use the $location service in a controller:

var app = angular.module('myApp', []);
<br>app.controller('customersCtrl',
 function($scope, $location) {<br>    $scope.myUrl = $location.absUrl();
<br>});

Note that the $location service is passed in to the controller as an argument. In order to use the service in the controller, it must be defined as a dependency.

Why use Services?

For many services, like the $location service, it seems like you could use objects that are already in the DOM, like the window.location object, and you could, but it would have some limitations, at least for your AngularJS application. AngularJS constantly supervises your application, and for it to handle changes and events properly, AngularJS prefers that you use the $location service instead of the window.location object.

Why do we need AngularJS services?

AngularJS services are substitutable objects that are wired together using dependency injection (DI). You can use services to organize and share code across your app. AngularJS services are: Lazily instantiated – AngularJS only instantiates a service when an application component depends on it.

Which is a Angular built-in service?

AngularJS built-in services starts with $, same as other built-in objects. AngularJS includes services for different purposes. For example, $http service can be used to send an AJAX request to the remote server. AngularJS also allows you to create custom service for your application.

The $http Service

The $http service is one of the most common used services in AngularJS applications. The service makes a request to the server, and lets your application handle the response.

Example

Use the $http service to request data from the server:

var app = angular.module('myApp', []);
<br>app.controller('myCtrl', function($scope, $http) {<br>  $http.get("welcome.htm").then(function (response) {<br>    $scope.myWelcome = response.data;<br>  });<br>});

This example demonstrates a very simple use of the $http service. Learn more about the $http service in the AngularJS Http Tutorial.

The $timeout Service

The $timeout service is AngularJS’ version of the window.setTimeout function.

Example

Display a new message after two seconds:

var app = angular.module('myApp', []);
<br>app.controller('myCtrl', function($scope, $timeout) {<br>  $scope.myHeader = "Hello World!";
<br>  $timeout(function () {<br>    $scope.myHeader = "How are you today?";<br>  }, 2000);<br>});<br>

The $interval Service

The $interval service is AngularJS’ version of the window.setInterval function.

Example

Display the time every second:

var app = angular.module('myApp', []);
<br>app.controller('myCtrl', function($scope, $interval) {<br>  $scope.
theTime = new Date().toLocaleTimeString();
<br>  $interval(function () {<br>    $scope.theTime = new Date().toLocaleTimeString();
<br>  }, 1000);<br>});

Create Your Own Service

To create your own service, connect your service to the module:

Create a service named&nbsp;
<code>hexafy</code>:app.service('hexafy',&nbsp;function() {<br>&nbsp;
&nbsp;this.myFunc&nbsp;=&nbsp;function&nbsp; ]
toString(16);<br>&nbsp;&nbsp;}<br>});

To use your custom made service, add it as a dependency when defining the controller:

Example

Use the custom made service named hexafy to convert a number into a hexadecimal number:

app.controller('myCtrl', function($scope, <strong>hexafy</strong>) {<br>  $scope.
hex = <strong>hexafy</strong>.myFunc(255);<br>});

Use a Custom Service Inside a Filter

Once you have created a service, and connected it to your application, you can use the service in any controller, directive, filter, or even inside other services. To use the service inside a filter, add it as a dependency when defining the filter:

The service hexafy used in the filter myFormat:

app.filter('myFormat',
[<strong>'hexafy'</strong>, function(<strong>hexafy</strong>) {<br>  return function(x) {<br>    return <strong>hexafy</strong>.myFunc(x);<br>  };
<br>}]);<br>

You can use the filter when displaying values from an object, or an array:

&lt;ul><br>  &lt;
li ng-repeat="x in counts">{{x | myFormat}}&lt;
/li><br>&lt;/ul><br>


There are the following two characteristics of AngularJS services:

  • Lazy instantiated: AngularJS application instantiates a service component when any application component depends on it.
  • Singletons: All components, those dependent on a service get a reference to the single instance generated by the service factory.

Structure of Idle AngularJS Application

Separation of concern is the main objective of AngularJS application. Our controller must be responsible for databinding with the view using $scope and contains some business logic. Controller does not contain any logic to fetch the data. AngularJS services manage the data fetching. In AngularJS application, each component has their own responsibilities so that each component can become more testable.

AngularJS Service

AngularJS internal services

AngularJS internally provides many services that can be used in our application. All the AngularJS internal service start with $ (dollar) sign. $http, $route, $location, $window, $q, etc are useful services provided by AngularJS.

AngularJS custom services

With AngularJS application, we can define our own service and we can use them whenever required. There are many ways to create Services in AngularJS. The following are two very simple ways to create service.

  1. Using service keyword

    Use the “service” keyword is the easiest way to create Service in AngularJS application. In the following code snippet, second parameter is service function in which we define the behaviour of the service. Once we define the service, we can use this service anywhere by injecting this service as dependency.
Defining service without dependency:  
  
var app = angular.module('myapp', []);  
  
app.service('myTestService', function(){  
   // write your service here  
   // define variable and methods   
  
});  

Defining service with dependency:

var app = angular.module('myapp', []);  
  
app.service('myTestService', ['$http', function($http){  
   // write your service here  
   // define variable and methods   
     
}]);  

2. Using factory method

Instead of defining the service directly using the “Service” keyword of the Angular module we can also use the Factory method and services will be created on request when defined by a factory function. The purpose of the service factory is to generate the single object that can be used for the rest of the application.

Defining service without dependency:

var app = angular.module('myapp', []);  
  
app.factory('myTestService', ['$http', function($http){  
   // write your service here  
   // define variable and methods   
  
}]); 

End to End example of application using AngularJS Service

The first step is to create AngularJS application. Following code snippet is use to create AngularJS application. In this example, I have created one JavaScript file named app.js and placed the following code in this file.

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

Second step is to create service and service definitions. In this example, I have created service in different file called “appService.js”. Paste the following code in this file. In this AngularJS service object, I have created one function called “add”. This function takes two argument and return the sum of these two.

appService.js

app.service('appService', function () {  
   this.add = function (a1, a2) {  
      return parseInt(a1) + parseInt(a2);  
   }  
})  

Third step is to create controller object. Controller is a bridge between service and view. Controller pass the value of both the textboxes to the service function by using $scope.

appController.j
s

app.controller("appController", function ($scope, appService) {  
   $scope.Add = function () {  
      $scope.total = appService.add($scope.digit1, $scope.digit2);  
   }  
});

Last step is to create an HTML file. In HTML file, we need to register all scripts which are created by above code in head section. We need to also include angular.js file. Now paste the following code to html file.

HTML file (TestAgularJs.html)

<html>  
<head>  
    <title>Understanding Services In AngularJS</title>  
    <script src="angular.js"></script>  
    <script src="app.js"></script>  
    <script src="appService.js"></script>  
    <script src="appController.js"></script>  
</head>  
<body ng-app="myapp">  
    <h4>Service Example</h4>  
      <div ng-controller="appController">  
        <div width="100%" style="padding-top:10px;">  
            <label>First Digit  : </label><input type="text" name="number" ng-model="digit1" />  
        </div>  
        <div width="100%" style="padding-top:10px;">  
            <label>Second Digit : </label><input type="text" name="number" ng-model="digit2" />  
        </div>  
        <div width="100%" style="padding-top:10px;">  
            <button ng-click="Add()">Add</button>  
        </div>  
        <div width="100%" style="padding-top:10px;">  
            <label>digit1 + digit2: </label><input type="text" name="number" ng-model="total" />  
        </div>  
    </div>  
</body>  
</html>  

Output

output

Introduction to AngularJS Services
Show Buttons
Hide Buttons