AngularJS Services

AngularJS Services

AngularJS are provided the concepts of Separation of Concerns using services architecture. A Services are JavaScript functions and important to do a specific tasks only. These make them specific entity which is updated and check. The controller and filter can call them as on requirement basis. The services are basically injected using dependency injection techniques of AngularJS. Other words we can say that, the AngularJS services are compatible objects that are wired together using dependency injection (DI). You can also use these services to organize, share code across your application.

AngularJS provide many inbuilt services such as $http, $route, $window, $location and so on. Each service is responsible for a specific task, such as $http, is utilized to create an Ajax call to get the server data.

There are two ways in which you can define the services of AngularJS:

  • Factory
  • Service

How to use factory method:

Using factory method, we can first create a factory and then declare method to it.

var mainApp = angular.module("mainApp", []);
      mainApps.factory('MathServices', function() {    
         var factory = {}; 
         factory.multiply = function(a, b) {
            return a * b
         }
         return factory;
      });

How to use Service Method

Using the service method, we create a service and then declare method to it. We have also injected an already applicable service to it.

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

For example:

This example will showcase all the above defined directives.

<html>
<head>
   <title>Angular JS Services</title>
   <script src="http://ajax.j2eebrain.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
   <h2>AngularJS Hello Application</h2>
   <div ng-app="mainApp" ng-controller="CalcController">
      <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>
      var mainApp = angular.module("mainApp", []);
      mainApps.factory('MathServices', function() {    
         var factory = {}; 
         factory.multiply = function(a, b) {
            return a * b
         }
         return factory;
      });
 
      mainApp.service('CalcService', function(MathService){
            this.square = function(a) {
            return MathService.multiply(a,a);
         }
      });
 
      mainApp.controller('CalcController', function($scope, CalcServices) {
            $scope.square = function() {
            $scope.result = CalcServices.square($scope.numbers);
         }
      });
   </script>
</body>
</html>

Creating Services

READ  Angularjs Module

Application developers are free to declare their own services by registering the service’s name and the service factory function with an Angular module. Service factory functions create the single object or function that represents the service to the application. The Object and the function returned by the service are injected into any component that specifies a dependency on the service.

AngularJS Internal Services

AngularJS internal service provides many services that we can use in our application &http is one example. All AngularJS internal services begin with $ sign.  Following are some other services like, $window, $location $route etc.

AngularJS services can be used within any Controller by just creating them as dependencies. Like this:

module.controller('FooController', function($http){
    //...
});
 
module.controller('BarController', function($window){
    //...
});

Registering Services

Via the module Application Programming Interface (API) services registered to modules. Commonly you can use the module factory API to register a service. For example:

var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
  var shinyNewServiceInstance;
  // factory function body that constructs shinyNewServiceInstance
  return shinyNewServiceInstance;
});

AngularJS Custom Services

We can create our own custom services in AngularJS application use them wherever required.. Following there are two simple ways:

var module = angular.module('myapp', []);
module.service('userService', function(){
    this.users = ['Meraj', 'Deepak', 'Himanshi'];
});

Or you can also use factory method such as:

module.factory('userService', function(){ 
    var fac = {};
     fac.users = ['Meraj', 'Deepak', 'Himanshi'];
     return fac;
 });

Both the methods of defining a service, function or object are valid. We will see the small difference between the factory () and service () method. For now just keep in mind that both these APIs provide a singleton service object that can be use used any controller, filter, and directive etc.

READ  AngularJS Introduction

Injecting Dependencies in Services

AngularJS provides out of the box support for dependency management. Dependency injection is a software design pattern that provides the removal of hard-coded dependencies and it’s important to modify them, whether at run time or compile time.