AngularJS - SPLessons

AngularJS Services

Chapter 23

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Services

AngularJS Services

shape Introduction

A service in Angular is a component that performs a specific job, like providing a timer, or providing the ability to communicate over HTTP.Normally, Directives will be used in-between the Model and the View, keeping them separate, but allowing them to communicate indirectly and move data back and forth.

If any changes are done in the input in the View, ng-model directive updates Model, and changes in Model are automatically pushed into the presentation of the page, the browser’s DOM. Services also allow us to separate concerns, even though it not directly related to a module, it might be logic to communicate over HTTP, or it might be an algorithm to compute the hash of a string, or it might be code that provides validation checks, or code that talks to local storage in the browser, or manage cookies sent from a server.

So, if any logic doesn’t set in a Model/View/directive,then Service is the best option as putting logic into that service makes the logic to easily use anywhere else in the application, because Controllers can view Services.

shape Description

Dependency Injection (DI) connects AngularJS Services which are substitutable objects. Services are mainly used to organise and helps in sharing code across the application and can carry out only specific tasks. AngularJS Services contains many useful functions like $http, but a user needs to create own services for most applications. Controllers, Directive, and Filters can call the functions as on when required.

Angular services are categorized into two types:

AngularJS provides many in-build services for example, $http, $route, $window, $location etc. Every service is responsible for a particular task. For example, $http is responsible to call AJAX to get the server data without reloading a page. In-build services are always prefixed with $ symbol.

AngularJS internal services

shape Description

AngularJS provides many in-build services and can be used in application page. For example,  $window,$http,$location, $route. These services can be utilized inside any controller by simply announcing them as dependencies.


module.controller('SPController', function($http){
  //...
});

module.controller('SPController', function($window){
  //...
});

AngularJS custom services

shape Description

Personal custom services can be defined and used anywhere in application. Custom services can be created in the following two ways.

Method-1: Using service method


module.service('MyService', function() {

this.method1 = function() {
   //..
}

this.method2 = function() {
  //..
}

});

Method-2: Using factory method


module.factory('MyService', function() {

var factory = {};

factory.method1 = function() {
  //..
}
factory.method2 = function() {
  //..
}
return factory;
});

In above example, MyService is defined in two different ways. Note that, for .service  service, methods are created using this.methodname. And in .factory,  a factory object is created and the methods are assigned to it.

shape Example


index.html

<html>
<head>
   <title>Angular JS Services</title>
  
</head>
<body>
   <h2>AngularJS Services</h2>
   
   <div ng-app="spApp" ng-controller="SPController">
      <p>Enter a number: <input type="number" ng-model="number" />
         <button ng-click="square()">X<sup>2</sup></button>
      <p>Result: {{result}}</p>
   </div>
   
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script src="App.js"></script>
    <script src="factory.js"></script>
    <script src="service.js"></script>
    <script src="Controller.js"></script>
    
</body>
</html>

Controller.js

mainApp.controller('SPController', function($scope, CalcService) {
            $scope.square = function() {
            $scope.result = CalcService.square($scope.number);
         }
  });

App.js

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

service.js

 mainApp.service('CalcService', function(MathService){
            this.square = function(a) { 
            return MathService.multiply(a,a); 
         }
});

factory.js

mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b 
         }
         return factory;
}); 

Output:

Summary

shape Key Points

  • AngularJS Services are connected together through Dependency Injection (DI).
  • AngularJS provides many in-build services like $http, $location, $window, $route etc can be utilized inside any controller by simply announcing them as dependencies.
  • custom services can be defined and used anywhere in application.