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

 

 

 

 

THREE QUERIES offers easy access to information about business, management, technology and spirituality that helps people and has grown from there. We provide an important knowledge base for those involved in managing, architecture and developing projects of all kinds. With weekly exclusive updates, we keep you in touch with the latest business, management, technology and spirituality thinking.

WE ARE CONNECTED ~ Follow us on social media to get regular updates and opinion on what's happening in the world of SharePoint, front-end, back end web technologies and project management. If you like this article, please share it and follow us at Facebook, Twitter, Instagram, Pinterest and LinkedIn

About Satyendra Mishra

Microsoft certified, motivated, energetic and accomplished SharePoint Consultant and Architect with 13+ years of work experience in Management, Architecture, Analytics, Development and Maintenance. He has been fortunate to be a part of over 20+ Web/Mobile/Software SharePoint and .Net projects delivery with various companies across different industry sectors. This has provided him a valuable insight and experience especially in successful implementation of technology solutions. Having very strong System Architecture, Technological, Management & Analytical Skills, Knowledge of Office 365, SharePoint, .Net, JavaScript, React, Angular, Azure, SQL. In 2016, he decided to start sharing the knowledge back to society in the form for content writing and blogging.
View all posts by Satyendra Mishra →

Leave a Reply

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