Services are singleton objects  or just like a javascript function to perform a specific task. Angular allow us to use these services with controllers, service, filter or directive.

Whenever we want to use service with these components, we will have to specify the service name along with the component. By doing so, component ask angular to load that particular service in the application. This method of injecting service is called dependency injection.


Watch the live demo or download code from the link given below.


How to use a service with components

To use a service, you will have to add it as a dependency with a component  such as controller, filter  or service. To add a service with component, you have to pass it as an argument.

For example:

using-services1

Here, we have to use $http service in the controller. So, we will have to add it within single quotes inside dependency section. Furthermore, if we use some function then, must use the service as an argument in the function.


Types of services

Services in angular are of two type:

  1. Built-in services
  2. Custom services

Built-in Service:

AngularJS provide us several built-in services. You can use these services to give your controller additional functionality.

For example, $http, $route, $filter and many more.

Built-in services always prefixed with $ sign.

As angular contains several built-in services. It is not possible to include all services in the blog. So, we are describing some of the important and commonly used services here. These are :

$http: This service is used to fetch data from the remote server by making XMLHttpRequest  from the browser.

Syntax:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
// GET request to remote server
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// when the response is available this call back is called
$scope.variablename = response.data.records;
}, function errorCallback(response) {
// called when server returns an error
});
});

$route: This service is used for linking url to controller and view. this service is used with ngView directives and $routeParams service. we also use  $routeProvider ‘s API to define the route.

$filter: This service is used to filter the data according to user requirement.

Syntax:

var filter = angular.module('filterExample', [])
filter.controller('filterCntrl', function($scope, $filter) {
$scope.varname = $filter('filtername')($input);
});

For the functionality and uses of more sevices you can check out this link.


Custom Services

AngulaJS also allow you to create your own services, known as custom services.

There are many methods to create your own services, but commonly used method are :

1. Service method 

To create a service using service method, follow the syntax given below:

modulename.service('servicename', function() {

this.maethodname1 = function() {
......
}
this.methodname2 = function() {
......
}
});

Note: We can also inject an already available service within the function.

angulrjs service code


2. Factory  method 

In the factory method of creating service, we first create the object of the factory then we assign method to it and at last, we return the factory object. Below syntax is used to create service using factory method.

modulename.factory('modulename', function() {
var factory = {};
factory.methodname1 = function() {
.............
}
factory.methodname2 = function() {
..............
}
return factory;
});

Creating a application

Let’s create an application using services which will perform the arithmetic operation.

First, you will need the angular.min.js and bootstrap.min.css file to connect your HTML code with angular and bootstrap.

This application is going to use both methods of creating custom services.

HTML File: index.html

<html>
<head>
<title>Angular JS Services</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" type="text/css" href= "css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href= "css/style.css">
<script type="text/javascript" src="js/app.js"></script>
</head>
<body ng-app = "mainApp" >
<center> <h1 class="h1">AngularJS- Custom Services Demo</h1> </center>
<div class="container">
<div class="demo-wrapper row">
<div class="col-md-4 col-md-offset-2 col-xs-12" border="1" ng-controller = "CalcController">
<div id="seen">
<div class="login">
<h2>Perform Airthmetic Operation</h2>
<hr/>
<p>Enter first number : <input type = "number" ng-model = "firstnumber" />
<p>Enter secand number: <input type = "number" ng-model = "secandnumber" /></p>
<button ng-click = "addition()">+</button>
<button ng-click = "multiplyr()">X</button>
<button ng-click = "divid()">/</button>
<button ng-click = "subs()">-</button>
<p>Result: {{ans}}</p>
</div>
</div>
</div>
<div class="col-md-4 col-md-offset-0 col-xs-12">
<div id="seen">
<div class="login">
<!--<h2>AngularJS Services Implementation</h2><hr><br><br>-->
<h2>Get Square Root For A Number</h2><hr/>
<div ng-controller = "CalcController">
<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Javascript File: app.js

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

mainApp.factory('calculate', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
factory.multiplyr = function(a, b) {
return a * b
}
factory.addition = function(a, b) {
return a + b
}
factory.subs = function(a, b) {
return a - b
}
factory.divid = function(a, b) {
return a / b
}
return factory;
});

mainApp.service('callcalculate', function(calculate){
this.square = function(a) {
return calculate.multiply(a,a);
}
this.multiplyr = function(a,b){
return calculate.multiplyr(a,b);
}
this.addition = function(a,b){
return calculate.addition(a,b);
}
this.subs = function(a,b){
return calculate.subs(a,b);
}
this.divid = function(a,b){
return calculate.divid(a,b);
}
});

mainApp.controller('CalcController',function($scope, callcalculate) {
$scope.square = function() {
$scope.result = callcalculate.square($scope.number);
}
$scope.multiplyr=function(){
$scope.ans= callcalculate.multiplyr($scope.firstnumber,$scope.secandnumber);
}
$scope.addition=function(){
$scope.ans= callcalculate.addition($scope.firstnumber,$scope.secandnumber);
}
$scope.subs=function(){
$scope.ans= callcalculate.subs($scope.firstnumber,$scope.secandnumber);
}
$scope.divid=function(){
$scope.ans = callcalculate.divid($scope.firstnumber,$scope.secandnumber);
}
});

CSS File: style.css

@import url(http://fonts.googleapis.com/css?family=Raleway);
.demo-wrapper{
min-height: 900px;
min-width: 300px;
}
.h1 {
margin: 40px auto !important;
}
.login h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}
.login hr{
border:0;
border-bottom:1px solid #ccc;
margin: 10px -40px;
margin-bottom: 10px;
}
.login{
width:100%;
border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 40px;
word-wrap: break-word;
}
.login p{
margin-top:8px;
font-size:16px;
}
.login hr {
margin-bottom: 30px;
}
input[type=text],input[type=number]{
width:99.5%;
padding: 10px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
} 

Conclusion

After reading above post, I am sure that you must be clear with the concept of angularjs services. Let us know about your feedback from the space provided below. Keep visiting our website and always be in touch with us for new coding tricks.