What are services and how to use them in AngularJS

Posted By : Kaushlendra Kumar Pal | 27-Feb-2018

Description : Welcome to my angularjs blog and in this blog we'll be learning about something called services in angularjs the services which we are going to learn in this blog are something which you should know when you are learning angularjs and they will allow you to have data in different controllers if you have like let's say you have an array of employees you are getting from your server-side languages like you have any file or any PHP file which generates a JSON response and you want to display them inside your website with the help of angularjs so what you will do is you will get that data from the server with HTTP angularjs service and then you will manipulate it somehow and you'll display that but what if you have like a lot of controllers then it would not be feasible to do an HTTP request in every of the controller what you like to do is you would like to have a single HTTP request done and then store it somewhere we call that as a service so a service is pretty much like creating a function in angularJS and then using it anywhere but angularjs services are singleton now but that what I mean is that only one instance of a service is created and the reference is passed now this would seem a little bit complicated but by the end of this blog I promise you guys that you will understand what I am trying to say here.

 

now let's start with services so, first of all, include your angular JS file and your script. So let's start the coding so first of all create an application and create the service first because we'll need to include something in controller to make that work so to create a service, let's say it creates it on random numbers let's just create the name as random and then as a function which would act as your service now what we are going to do here is we are going to make use of the "this keyword" because this keyword points to this service which we are working with so this means random so, first of all, let's just get a random number from math dot random and let's just make it a little pretty by flooring it down don't forget to multiply by ten so that you don't get zero always now I'll make use of this.generate as a function now this would be a function and what I'm going to do is I'm just going to return the variable num now this number variable which I have declared with var is the private property of the service and I can't access it anywhere outside the service but I can access properties or values associated with this keyword where ever I included in the service so this is a thing you could note so now let's just create a controller application.controller and I'll just include the name random of my service if you don't do that then you won't be able to include or use your service inside your controller so our simple application is ready now let's just take a look at the browser :

 

HTML

<body ng-app="mainApp" ng-controller="app">
	<button ng-click="generateRandom()">Generate Random Number</button>
	<br>{{randomNumber}}
</body>

 

JS

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

application.service('random', function() {
	var num = Math.floor(Math.random()*10);
	this.generate = function() {
		return num;
	};
});

application.controller('app', function($scope, random) {
	$scope.generateRandom = function() {
		$scope.randomNumber = random.generate();
	};
});

 

So from above code will get a button which generates random numbers and when I click on it you will get random numbers. I told you that services in angularjs are singleton and now I'm going to show you what does that mean so I told you that services are singleton now this can be best proved by clicking on this button again so you see when I click on this button it doesn't generate any more random numbers now why is it this so now I'm gonna explain gonna explain this and simple words here so when the angularjs ran and when I clicked on this button first time what angularjs did is it ran the service first time and it kinda just passed the reference of the service so what happened is when this function was called the first time the way the first time angularjs run the service and then pass the reference of the service and created a reference of the service. Now when I call this again then instead of running whole code again it will pass the service which it created the previous one to here again So since angularjs services are singleton that means they would just create an instance in just once and would continuously pass the references of that when it is called what would happen is you will always get the same number because a unique number is created the first time but not every time so that's how angularjs services works and this is really gonna be a handy thing you could have. if you're getting some data from the server and you want to display it on in different controllers but you don't want to just copy and paste the whole code again and again. So this was all about services and angularjs.

About Author

Author Image
Kaushlendra Kumar Pal

Kaushlendra is an experienced Java Developer with comprehensive mastery of all Java packages. Able to Write well designed, testable, efficient code as per the requirements and handle different types of issues as well as functions.

Request for Proposal

Name is required

Comment is required

Sending message..