What is AngularJS Services

AngularJS Service is basically a function or object, which has scope at maximum AngularJS application level only. There are almost 30 built-in services. Few of them are replacement of legacy JavaScript functions. As soon as we go through this article, we’ll see the usage, application and history of AngularJS services one by one.

A question with a word WHY is always important to learn, understand ultimately getting the knowledge of new concept. So let’s keep this magical and most powerful word here as well.

WHY, AngularJS Service?

Let’s take an example first. This will help us to increase the curiosity of getting its answer anyhow.

var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $location) {
$scope.myUrl = $location.absUrl();
});

Above example will set value of AngularJS property “myUrl” to the current URL of web page where this AngularJS code is written.

Is it not new? Oh, we already have a JavaScript property window.location.href which returns same value. Then which one is better to use?

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.

Example of AngularJS Services

  1. $http Service

 It is most commonly used in AngularJS. $http is an XMLHttpRequest object for requesting external data. This service makes call to the server and capture the response.

 var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $http) {
$http.get(“index.html”).then(function (response) {
$scope.homePageResponse = response.data;
});
});

 Above example uses .get () shortcut method of $http. There are two ways to represent these methods, which are provided below. Anyone of them can be used.

$http.get(“index.html”)

OR

$http({

method : “GET”,

url : “index.html”

})

There are several other shortcut methods of $http

.delete()

.get()

.head()

.jsonp()

.patch()

.post()

.put()

Error Handling

To handle errors in $https, we need to use the cases for success and error. Let’s understand it using an example:

var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $http) {
$http.get(“index.html”)
.then(function(response) {
//First function handles success
$scope.content = response.data;
}, function(response) {
//Second function handles error
$scope.content = “Something went wrong”;
});
});

JSON as Data

 Data you get in response is expected to be in JSON format. JSON is great way to transfer the data across multiple platforms which support HTML. Data in JSON format will looks like below:

{ “records”:[ {“Name”:”XYZ”,”City”:”New Delhi”,”Country”:”India”}, {“Name”:”ABC”,”City”:”México D.F.”,”Country”:”Mexico”} ] }

Here “records” is an array containing data in JSON format.

var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $http) {
$http.get(“index.html”).then(function(response) {
$scope.smData = response.data.records;
});
});

Here “smData” AngularJS property will be populated with an array of records in JSON format. This collection can be used to render data on web page.

Output

  • XYZ, India
  • ABC, Mexico
  1. $timeout Service

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

var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $timeout) {
$scope.smHeader = “Hello World!”;
$timeout(function () {
$scope.smHeader = “smHeader value is changed from Hello World! To this text after 5 seconds”;
}, 5000);
});

In above example smHeader will set to “Hello World!” initially but after 5 seconds it will be changed to “smHeader value is changed from Hello World! to this text after 5 seconds”. 

  1. $interval Service

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

var app = angular.module(‘smApp’, []);
app.controller(‘smController’, function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});

The anonymous will be executed after every 1 second.

Create Your Own AngularJS Service

We can use AngularJS API to create our own custom AngularJS service. Let’s see and example below:

var app = angular.module(‘smApp’, []);

app.service(‘MyCustomService’, function() {
this.multiplyByTen = function (x) {
return x * 10;
}
});

Here, MyCustomService is the name of AngularJS service whereas muliplyByTen() is a method in service.

We need to use a controller for consuming this AngularJS service.

app.controller(‘smController’, function($scope, MyCustomService) {
$scope.newValue = MyCustomService.multiplyByTen(10);
});

It will set value to AngularJS property “newValue” to 100.

 

Be  Connected…

Satyendra Mishra

About Satyendra Mishra

Satyendra is a Technical Project Manager with 12+ years of experience on Project Management, Microsoft Technologies including ASP.NET, ASP.NET MVC, C#, SharePoint (On premises & Office 365), JavaScript Framework (AngularJS) and related technologies. He is a person with belief, sky is limit for a hard working and dedicated individual. That’s why he devoted himself to field of Software Development and now both are growing with each other. Every year for him turned out to be best year and he received enormous support and love from his companies and his clients from around the world. Now with vast knowledge of software development and its outsourcing process, he decided to move himself into knowledge sharing. Keep a fact in your mind about the comfort level of your clients and this will make you king/queen of your area.
View all posts by Satyendra Mishra →