Unit 5- Dependency Injection, Services

    5.1 What is dependency injection?

  • AngularJS comes with a built-in dependency injection mechanism. It facilitates you to divide your application into multiple different types of components which can be injected into each other as dependencies.
  • Dependency Injection is a software design pattern that specifies how components get holds of their dependencies. In this pattern, components are given their dependencies instead of coding them within the component.
  • Modularizing your application makes it easier to reuse, configure and test the components in your application.
  • Following are the core types of objects and components:
    o value
    o factory
    o service
    o provider
    o constant

    1. Value:

    In AngularJS, value is a simple object. It can be a number, string or JavaScript object. It is used to pass values in factories, services or controllers.

    Example
    //Define a module
    var myModule = angular.module("myModule", []);

    //create a value object and pass it a data.
    myModule.value("numberValue", 100);
    myModule.value("stringValue", "abc");
    myModule.value("objectValue", { val1 : 123, val2 : "abc"} );

    Here, values are defined using the value() function on the module. The first parameter specifies the name of the value, and the second parameter is the value itself. Factories, services and controllers can now reference these values by their name.

    Injecting a value
    To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.

    var myModule = angular.module("myModule", []);
    myModule.value("numberValue", 100);
    myModule.controller("MyController", function($scope, numberValue) {
    console.log(numberValue);
    });

    2. Factory

    Factory is a function that is used to return value. When a service or controller needs a value injected from the factory, it creates the value on demand. It normally uses a factory function to calculate and return the value.

    Example
    var myModule = angular.module("myModule", []);
    myModule.factory("myFactory", function() {
    return "a value";
    });

    myModule.controller("MyController", function($scope, myFactory) {
    console.log(myFactory);
    });

    Injecting values into factory
    To inject a value into AngularJS controller function, add a parameter with the same when the value is defined.

    var myModule = angular.module("myModule", []);
    myModule.value("numberValue", 100);
    myModule.controller("MyController", function($scope, numberValue) {
    console.log(numberValue);
    });

    3. Service

    In AngularJS, service is a JavaScript object which contains a set of functions to perform certain task. Services are created by using service () function on a module and then injected into controllers.

    //define a module
    var mainApp = angular.module("mainApp", []);

    //create a service which defines a method square to return square of a number.
    mainApp.service('CalcService', function(MathService){
    this.square = function(a) {
    return MathService.multiply(a,a);
    }
    });

    //inject the service "CalcService" into the controller
    mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
    $scope.number = defaultInput;
    $scope.result = CalcService.square($scope.number);
    $scope.square = function() {
    $scope.result = CalcService.square($scope.number);
    }
    });

    4. Provider

    In AngularJS, provider is used internally to create services, factory etc. during config phase (phase during which AngularJS bootstraps itself). Provider is a special factory method with a get() function which is used to return the value/service/factory.

    //define a module
    var mainApp = angular.module("mainApp", []);

    //create a service using provider which defines a method square to return square of a number.
    mainApp.config(function($provide) {
    $provide.provider('MathService', function() {
    this.$get = function() {
    var factory = {};
    factory.multiply = function(a, b) {
    return a * b;
    }
    return factory;
    };
    });
    });

    5. Constants

    You cannot inject values into the module. Config () function. Instead constants are used to pass values at config phase.
    mainApp.constant("configParam", "constant value");
    Example

    <html> <head><title>AngularJS Dependency Injection</title> </head>
    <body>
    <div ng-app = "mainApp" ng-controller = "CalcController">
    <p>Enter a number: <input type = "number" ng-model = "number" /></p>
    <button ng-click = "square()">X<sup>2</sup></button>
    <p>Result: {{result}}</p>
    </div> <script src = "angular.min.js"></script>

    <script>
    var mainApp = angular.module("mainApp", []);
    mainApp.config(function($provide) {
    $provide.provider('MathService', function() {
    this.$get = function() {
    var factory = {};
    factory.multiply = function(a, b) {
    return a * b;
    }
    return factory;
    };
    });
    });

    mainApp.value("defaultInput", 10);

    mainApp.factory('MathService', 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, CalcService, defaultInput) {
    $scope.number = defaultInput;
    $scope.result = CalcService.square($scope.number);
    $scope.square = function() {
    $scope.result = CalcService.square($scope.number);
    }
    });
    </script>
    </body>
    </html>

    5.2 Understanding services

  • AngularJS service are JavaScript function or object, who’s responsible to perform specific tasks and can be reused throughout the application.
  • It provide many inbuilt services. In AngularJS services starts with “$”.
  • Example: $http, $window, $location etc.
  • These AngularJS services interact with controller, model or custom directives.

    5.3 Using built-in service

    $anchorScroll $exceptionHandler $interval $rootScope
    $animate $filter $locale $sceDelegate
    $cacheFactory $httpParamSerializer $location $sce
    $templateCache $httpParamSerializerJQLike $log $templateRequest
    $compile $http $parse $timeout
    $controller $httpBackend $q $window
    $document $interpolate $rootElement

    All the Angular services are lazy instantiated and singleton. It means AngularJS framework instantiates a service when an application component depends on it. Also, all the components share the same instance of a service.
    1. $interval Service
  • AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript.
  • The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing.
  • The $interval service executes the specified function on every specified milliseconds duration.
  • Syntax: $interval(fn, delay, [count], [invokeApply], [Pass]);
    Example:

    <html >
    <head>
    <script src="~/Scripts/angular.js"></script>
    </head>
    <body ng-app="myApp">
    <div ng-controller="myController">
    {{counter}}
    </div>
    <script>
    var myApp = angular.module('myApp', []);
    myApp.controller("myController", function ($scope, $interval) {
    $scope.counter = 0;
    var increaseCounter = function () {
    $scope.counter = $scope.counter + 1;
    }
    $interval(increaseCounter, 1000);
    });
    </script>
    </body>
    </html>

    2. $window Service
  • AngularJs includes $window service which refers to the browser window object.
  • In the JavaScript, window is a global object which includes many built-in methods like alert(), prompt() etc.
  • The $window service is a wrapper around window object, so that it will be easy to override, remove or mocked for testing. It is recommended to use $window service in AngularJS instead of global window object directly.
  • Example:

    <html>
    <head>
    <script src="~/Scripts/angular.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myController">
    <button ng-click="DisplayAlert('Hello World!')">Display Alert</button>
    <button ng-click="DisplayPrompt()">Display Prompt</button>
    <script>
    var myApp = angular.module('myApp', []);
    myApp.controller("myController", function ($scope, $window) {
    $scope.DisplayAlert = function (message) {
    $window.alert(message);
    }

    $scope.DisplayPrompt = function () {
    var name = $window.prompt('Enter Your Name');
    $window.alert('Hello ' + name);
    }
    });
    </script>
    </body>
    </html>

    3. $timeout Service

    $timeout in AngularJs is similar to the window.setTimeout() function in JavaScript.
    Usage of the $timeout service allows the developer to set some time delay to execute the methods and functions as per the requirement.

    Example:
    <html>
    <head>
    <script src="~/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script type="text/javascript">
    var app = angular.module('firstApp', []);
    app.controller('firstCtrl', function ($scope, $timeout) {
    $scope.msg="Ahoy!"
    $timeout(function () {
    $scope.msg = "Save the planet!";
    }, 2000);
    });
    </script>
    </head>
    <body>
    <div ng-app="firstApp" ng-controller="firstCtrl">
    <p>$timeout Service Example</p>
    <b>{{msg}}</b>
    </div>
    </body>
    </html>
    It must be noted that in the code given above, we are changing the message after 4 seconds. This is done by using the $timeout service. We have passed $timeout as an argument to the controller in the example given above. To use service in controller, $timeout must be passed as a parameter.

    4. $location Service

    The $location service has methods which return information about the location of the current web page.
    Example
    <html>
    <head>
    <script src="angular.min.js"></script>
    </head>
    <body ng-app="locationService" >
    <h4>Click on the button to see the current URL</h4>
    <div ng-controller="locationServiceController">
    <button ng-click="seeURL()">See URL</button>
    <p>Current URL is :: {{currentURL}}</p>
    </div>
    <script>
    var app = angular.module('locationService', []);
    app.controller('locationServiceController',
    ['$scope', '$location', function ($scope, $location) {
    $scope.seeURL = function () {
    $scope.currentURL = $location.absUrl();
    }
    }]);
    </script>
    </body>
    </html>

    5.4 Creating custom service

  • AngularJS allows us to create our own custom service.
  • Once we have created a service and connected it to our application, we can use the service in any controller, directive, filter or even inside other services
  • Syntax:
    app.service(‘name of the service’, function());

    Example:

    <html>
    <head>
    <script src="angular.min.js"></script>
    </head>
    <body>
    <div ng-app=”myApp” ng-controller=”myctrl”>
    <h2>The octal value of 330 is:</h2>
    <h2>{{octal}}</h2>
    </div>
    <script>
    var app = angular.module(‘myApp’, []);
    app.service(‘demoservice',function()
    { this.myFunc= function(x)
    {Return x.toString(7);}
    }
    });

    app.controller(‘myctrl’,function($scope,demoservice)
    {
    $scope.octal=demoservice.myFunc(330);
    });
    </script>
    </body>
    </html>

    5.5 Injecting dependency in service

    Service is defined sing service() function & it is then injected into controllers.
    Example:
    demo.js
    var myapp = angular.module(‘myApp’, []);

    // create service
    myapp.service(‘calculate’,function()
    {
    this.add= function(x,y)
    {Return a+b;};
    this.sub= function(x,y)
    {Return a-b;};
    this.multi= function(x,y)
    {Return a*b;}
    });

    //inject this service in controller like built-in services
    app.controller(‘myctrl’,function($scope,$http,calculate)
    {
    $scope.no1=3;$scope.no2=2;
    $scope.result=calculate.add($scope.no1,$scope.no2);
    $scope.resultSub=calculate.sub($scope.no1,$scope.no2);
    $scope.resultMult=calculate.multi($scope.no1,$scope.no2);
    Console.log($scope.result);
    });

    index.html

    <html>
    <head>
    <script src="angular.min.js"> </script>
    </head>
    <body>
    <h3>AngularJS Custom Service</h3>
    <div ng-app=”myApp” ng-controller=”myctrl”>
    <p>Result of Addition:{{reslt}}</p>
    <p>Result of Substraction:{{ resultSub }}</p>
    <p>Result of Multiplication:{{ resultMult }}</p>
    </div>
    </body>
    </html>

No comments:

Post a Comment