Introduction To AngularJS Services

Angular Services

AngularJS is a JavaScript Framework, which is very powerful and its library is written in JavaScript. This framework is used to make single page applications. From this definition, you should get an idea that if we want to make a Single Page application, AngularJS is the answer as the most powerful JavaScript Framework. AngularJS extends HTML with new attributes. AngularJS allows us to write the applications in a clean Model-View-Controller way.

AngularJS Services

A Service is a function or an object; it is limited to our AngularJS application. We can make our own Services and can use one of many inbuilt Services. The Services are injected, using dependency injection mechanism. AngularJS has many inbuilt Services. Services are JavaScript functions, which are responsible to do a specific task only. This is the property of individual identity, which is maintainable and testable. Thus, making separation of concerns possible, i.e. the property of AngularJS. Some examples of the inbuilt Services are $https, $route, $location, $window etc. Angular only instantiates a Service when an application component depends on it. Each component is dependent on a Service, which gets a reference to the single instance generated by the Service factory.

Using an inbuilt service

Let’s use an inbuilt Service to check what will be the benefit and how we can use the Services. Let’s use $location, $location is a Service that has methods, which returns information about the location of the current Webpage. Now, we will also see the use of dependency injection mechanism. The Service will be defined as a dependency.

Example

Service (Service.js)

  1. var app = angular.module('myApp', []);  
  2.    app.controller('customersCtrl'function($scope, $location) {  
  3.   // $scope.myUrl = $location.absUrl(); 
  4.    $scope.myCurrentUrl= $location.absUrl(); 
  5. });   

View

  1. <html xmlns="http://www.w3.org/1999/xhtml">    
  2. <head>    
  3.     <title>Angular Services</title>    
  4.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>    
  5.     <script src="Service.js"></script>    
  6. </head>    
  7. <body>    
  8.     <div ng-app="myApp" ng-controller="customersCtrl">    
  9.         <p>The url of this page is:</p>    
  10.         <p>{{myCurrentUrl}}</p>    
  11.     </div>    
  12. </body>    
  13. </html>     
Now, if we run this, we will get an output, as shown below.

 

Here, in this example, we have used inbuilt Service $location that has the method, which returns the current location of the Web page.
  1. $location.absUrl()   

Creating a Service

Now, the question arises: What if we don’t want to use inbuilt Services and want to create our own Service for some functionality? How can we achieve that? We can do this by creating our own Services. We can create the Services, using three ways.

  1.  By using factory
  2.  By using Service
  3.  By using provider

First of all, we create a module named myApp,

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

Using Factory Method

Syntax
  1. myApp.factory('factoryName',function(){  
  2. return factoryObj;  
  3. });  
Example
  1. myApp.service('serviceName',function(){ });    
  2.  Example:  
  3. myApp.service('SumService'function (MathService) {    
  4.     this.sum = function (a) {    
  5.         return MathService.Sum(a, a);    
  6.     }    
  7. });   

In this method, we have first defined a factory and then we have assigned a method to the factory.

Using Service Method

In this, a new keyword is used to instantiate it. We will get an instance of the function passed to the Service. This object instance becomes the Service Object that AngularJS registers and is injected, wherever required. This keyword is used to add properties and functions to this Service object.

Syntax

  1. myApp.service('serviceName',function(){ });  
Example
  1. myApp.service('SumService'function (MathService) {    
  2.     this.sum = function (a) {    
  3.         return MathService.Sum(a, a);    
  4.     }    
  5. });   

In this method, we have defined a Service and then assign method to it. This keyword adds properties and functions to the Service object here.

Using Provider

The Providers are the only Service that we pass into .config() function. These are used only when we have to provide module wide configuration for the Service object before making it available. It uses $get() function to return the value.

Syntax

  1. myApp.provider('providerName',function(){ })   
For configuring a provider,
  1. app.config(function(providerNameProvider){});  

Now, we will see how we can use them.

Let’s understand this with an example given below.

View

  1. <html>    
  2. <head>    
  3.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>    
  4.     <!--<script src="MyService.js"></script>-->    
  5.     <script src="MyService.js"></script>    
  6. </head>    
  7. <body>    
  8.        
  9.         <div ng-app="myApp" ng-controller="myController">    
  10.             <p>Message From Angular Service: {{service}}</p>    
  11.             <p>Message From Angular Factory: {{factory}}</p>    
  12.             <p>Message From Angular Provider:{{provider}}</p>    
  13.         </div>    
  14.        
  15.     
  16. </body>    
  17. </html>     

Service (MyService.js)

  1. var app = angular.module('myApp', []);    
  2.     
  3. //using Service    
  4. app.service('myAngularService'function () {    
  5.     this.message = '';    
  6.     this.setMessage = function (newMessage) {    
  7.         this.message = newMessage;    
  8.         return this.message;    
  9.     };    
  10. });    
  11.     
  12. //using factory    
  13. app.factory('myAngularFactory'function () {    
  14.     var obj = {};    
  15.     obj.message = '';    
  16.     obj.setMessage = function (newMessage) {    
  17.         obj.message = newMessage;    
  18.     };    
  19.     return obj;    
  20. });    
  21.     
  22. //using provider    
  23. app.provider('myAngularP'function () {    
  24.     var returnMessage = '';    
  25.     this.setMessage = function (newMessage) {    
  26.         returnMessage = newMessage;    
  27.     };    
  28.     this.$get = function () {    
  29.         return {    
  30.             message: returnMessage    
  31.         };    
  32.     };    
  33. });    
  34.     
  35. //configuring provider    
  36. app.config(function (myAngularPProvider) {    
  37.     myAngularPProvider.setMessage("This is using Provider");    
  38. });    
  39.     
  40. //defining controller    
  41. app.controller('myController'function ($scope, myAngularService, myAngularFactory, myAngularP) {    
  42.     $scope.service = myAngularService.setMessage("this is using Service");    
  43.     
  44.     myAngularFactory.setMessage("This is using Factory ");    
  45.     $scope.factory = myAngularFactory.message;    
  46.     
  47.     $scope.provider = myAngularP.message;    
  48. });    

Now, we can see all the three ways. If we run this, we will get the output given below.

We have injected the Service as a dependency here. By using Service method, we get an instance of a function passed to “module.service” and by using factory method, we get the value, which is returned by invoking the function reference, which is is passed to module.factory.

In this article, we have seen how the Services can be created as per use and how can we use inbuilt Services. Provide your valuable feedback after going through the article.

Up Next
    Ebook Download
    View all
    Learn
    View all