Services are one of the important concepts in AngularJS. In general, Services are functions that are responsible for specific tasks in an application. AngularJS services are designed based on two principles.
- Lazily instantiated: Angular only instantiates a service when an application component depends on it using dependency injection to make Angular the codes robust and less error-prone.
- Singletons: Each component is dependent on a service that gets a reference to the single instance generated by the service factory.
AngularJS supports the concepts of "Separation of Concerns" using a services-oriented architecture and it is at the heart when designing an AngularJS application. Controllers, filters, or directives can call them on the basis of requirements. The controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulate it.
Services provide a method to share data across the lifetime of the AngularJS application. It provides a method to communicate data across the controllers in a consistent way. This is a singleton object and it is instantiated only once per application. It is used to organize and share data and functions across the application.
Thus a service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters, and so on. Thus we can divide our application into logical units. The business logic or logic to call HTTP URL to fetch data from the server can be put within a service object.
Putting business and other logic within services has many advantages. First, it fulfills the principle of separation of concerns or segregation of duties. Each component is responsible for its own work making application code more manageable and more testable. Thus we can quickly write tests for our services making them robust and less error-prone.
AngularJS provides many built-in services, for example, $http, $route, $window, $location, and so on. Each service is responsible for a specific task, for example, $http is used to make an Ajax call to get the server data. $route defines the routing information and so on. Built-in services are always prefixed with the $ symbol.
AngularJS internal services
AngularJS internally provides many services that we can use in our application. $http is one example. There are other useful services, such as $route, $window, $location, and so on. Some of the commonly used services in any AngularJS application are listed below.
- $window: Provide a reference to a DOM object.
- $Location: Provides a reference to the browser location.
- $timeout: Provides a reference to the window.set timeout function.
- $Log: Used for logging.
- $sanitize: Used to avoid script injections and display raw HTML on page.
- $Rootscope: Used for scope hierarchy manipulation.
- $Route: Used to display browser-based path in browser URL.
- $Filter: Used for providing filter access.
- $resource: Used to work with Restful API.
- $document: Used to access the window. Document object.
- $exceptionHandler: Used for handling exceptions.
- $q: Provides a promise object.
Here, the question arises in our mind that we had window, window. Location, document, and timeout in the DOM in JavaScript, so why does $window, $location, $document, $timeout in terms of services? The reason behind this is to support dependency injection and to more easily test using a mocked version of $window, $location, $document, and $timeout services.
what is the mocked version and what is mocking?
Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to test you replace the other objects with mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.
Let's understand some of the AngularJS internal services.
$window Service
Example-1
<!DOCTYPE html>
<html ng-app="WindowsServiceapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script>
angular.module("WindowsServiceapp", [])
.controller("WindowsServicectrl", function ($scope, $window)
{
$scope.dissplayAlert = function (msg)
{
$window.open("http://www.google.com", "test", 'height=200,width=550');
$window.document.write("Testing....");
$window.alert(msg);
}
});
</script>
</head>
<body>
<div ng-app="WindowsServiceapp">
<div ng-controller="WindowsServicectrl">
<div>
<button name="btn" ng-click="dissplayAlert('clicked')">click me </button>
</div>
</div>
</div>
</body>
</html>
Output

Here the “WindowsServicectrl” $window service is injected and shows an alert and opening pop-up window in the preceding example. Note that $windows is not the same window object. To keep the window object an injectable component for manipulation of AngularJS that has created a wrapper on the window object.
$http Services
Let us understand the $http service that makes a service call for server communication. Now we will see a simple HTTP service that is used to fetch the data from an SQL Server database.
We have an employee table that contains some employee information as in the following.

We have a web API that is a source of a data layer that connects to a database and we need to call it using Angular code.
Example 2
public class EmployeeAPIController : ApiController
{
private EmployeeEntities db = new EmployeeEntities();
public IEnumerable<Employee> GetEmployees()
{
return db.Employees.AsEnumerable();
}
}
Service
app.service('EmployeeService', function ($http)
{
this.getAllEmployee = function ()
{
return $http.get("/api/EmployeeAPI"); // Calling the web api here
}
});
Controller
app.controller('EmployeeController', function($scope, EmployeeService)
{
GetAllRecords();
function GetAllRecords()
{
var promiseGet = EmployeeService.getAllEmployee();
promiseGet.then(function(pl)
{
$scope.Employees = pl.data;
},
function(errorPl)
{
$log.error('Some Error in Getting Records.', errorPl);
});
}
});
Module
var app;
(function()
{
app = angular.module("EmployeeModule", []);
})();
HTML Page
<html ng-app="EmployeeModule">
<head>
<style type="text/css">
table.table-style {
font-family: verdana, arial, sans-serif;
font-size: 11px;
color: #333333;
border-width: 1px;
border-color: #3A3A3A;
border-collapse: collapse;
border: 2px solid gray;
background-color: #f5f5f5;
}
table.table-style th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #FFA6A6;
background-color: #D56A6A;
color: #ffffff;
}
table.table-style tr:hover td {
cursor: pointer;
}
table.table-style tr:nth-child(even) td {
background-color: #F7CFCF;
}
table.table-style td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #FFA6A6;
background-color: #ffffff;
}
</style>
</head>
<body data-ng-controller="EmployeeController">
<table class="table-style">
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Birth Day</th>
<th>Gender</th>
<th>HireDate</th>
</tr>
<tbody data-ng-repeat="emp in Employees">
<tr>
<td>
<span>{{emp.EmployeeID}}</span>
</td>
<td>
<span>{{emp.Name}}</span>
</td>
<td>
<span>{{emp.Title}}</span>
</td>
<td>
<span>{{emp.BirthDate}}</span>
</td>
<td>
<span>{{emp.Gender}}</span>
</td>
<td>
<span>{{emp.HireDate}}</span>
</td>
</tr>
</tbody>
</table>
</body>
</html>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/EmployeeScripts/Module.js"></script>
<script src="~/Scripts/EmployeeScripts/Service.js"></script>
<script src="~/Scripts/EmployeeScripts/Controller.js"></script>
Output

User Defined Services
Let us create some of the services that we need to write based on our requirements. We will create a calculation web page that does Addition, Subtraction, Multiplication, and Division. We will create a service called "CalculatorService" and call this calculator service in the controller. From the controller, the service results are assigned to the Scope object and finally shown to the UI.
Example 3





ASHISH SHARMAPosted Sep 2, 2019, 12:56 PM
Hi Pradeep Thanks for the above example 7 . Can you please explain the same example using angularjs provider?
Asfend YarPosted Feb 29, 2016, 2:17 PM
nice
Pradeep SahooPosted May 9, 2015, 12:27 AM
Thank you all.
Santhakumar MunuswamyPosted May 7, 2015, 2:47 PM
Thanks for nice article
Manoj BhoirPosted May 7, 2015, 11:37 AM
Good one
Shridhar SharmaPosted May 7, 2015, 11:06 AM
nice one.