Sunday, January 10, 2021

Dependency Injection in AngularJS with Example

 What is Dependency Injection in AngularJS?

Dependency Injection is a software design pattern that implements inversion of control for resolving dependencies.

Inversion of Control: It means that objects do not create other objects on which they rely to do their work. Instead, they get these objects from an outside source. This forms the basis of dependency injection wherein if one object is dependent on another; the primary object does not take the responsibility of creating the dependent object and then use its methods. Instead, an external source (which in AngularJS, is the AngularJS framework itself) creates the dependent object and gives it to the source object for further usage.

So let's first understand what a dependency is.

AngularJS - Dependency Injection

The above diagram shows a simple example of an everyday ritual in database programming.

  • The 'Model' box depicts the "Model class" which is normally created to interact with the database. So now the database is a dependency for the "Model class" to function.
  • By dependency injection, we create a service to grab all the information from the database and get into the model class.

In the remainder of this tutorial, we will look more at dependency injection and how this is accomplished in AngularJS.

In this tutorial, you will learn-

  • Which Component can be Injected as a Dependency In AngularJS
  • Example of Dependency Injection
    • Value component
    • Service

Which Component can be Injected as a Dependency In AngularJS

In Angular.JS, dependencies are injected by using an "injectable factory method" or "constructor function".

These components can be injected with "service" and "value" components as dependencies. We have seen this in an earlier topic with the $http service.

We've already seen that the $http service can be used within AngularJS to get data from a MySQL or MS SQL Server database via a PHP web application.

The $http service is normally defined from within the controller in the following manner.

	 sampleApp.controller ('AngularJSController', function ($scope, $http) 

Now when the $http service is defined in the controller as shown above. It means that the controller now has a dependency on the $http service.

So when the above code gets executed, AngularJS will perform the following steps;

  1. Check to see if the "$http service" has been instantiated. Since our "controller" now depends on the "$http service", an object of this service needs to be made available to our controller.
  2. If AngularJS finds out that the $http service is not instantiated, AngularJS uses the 'factory' function to construct an $http object.
  3. The injector within Angular.JS then provides an instance of the $http service to our controller for further processing.

Now that the dependency is injected into our controller, we can now invoke the necessary functions within the $http service for further processing.

Example of Dependency Injection

Dependency injection can be implemented in 2 ways

  1. One is through the "Value Component"
  2. Another is through a "Service"

Let's look at the implementation of both ways in more detail.

1) Value component

This concept is based on the fact of creating a simple JavaScript object and pass it to the controller for further processing.

This is implemented using the below two steps

Step 1) Create a JavaScript object by using the value component and attach it to your main AngularJS.JS module.

The value component takes on two parameters; one is the key, and the other is the value of the javascript object which is created.

Step 2) Access the JavaScript object from the Angular.JS controller

<! DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>

</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="sampleApp">

<div ng-controller="AngularJSController">
    <h3> Guru99 Global Event</h3>
    {{ID}}
</div>
<script>

    var sampleApp = angular.module('sampleApp',[]);
    sampleApp.value("TutorialID", 5);
    sampleApp.controller('AngularJSController', function($scope,TutorialID) {
        $scope.ID =TutorialID;
    });

</script>
</body>
</html>

In the above code example, the below main steps are being carried out

  1. sampleApp.value("TutorialID", 5);

The value function of the Angular.JS JS module is being used to create a key-value pair called "TutorialID" and the value of "5".

  1. sampleApp.controller('AngularJSController', function ($scope,TutorialID)

The TutorialID variable now becomes accessible to the controller as a function parameter.

  1.  $scope.ID =TutorialID;

The value of TutorialID which is 5, is now being assigned to another variable called ID in the $scope object. This is being done so that value of 5 can be passed from the controller to the view.

  1. {{ID}}

The ID parameter is being displayed in the view as an expression. So the output of '5' will be displayed on the page.

When the above code is executed, the output will be shown as below

AngularJS - Dependency Injection

2) Service

Service is defined as a singleton JavaScript object consisting of a set of functions that you want to expose and inject in your controller.

For example, the "$http" is a service in Angular.JS which when injected in your controllers provides the necessary functions of

( get() , query() , save() , remove(), delete() ).

These functions can then be invoked from your controller accordingly.

Let's look at a simple example of how you can create your own service. We are going to create a simple addition service which adds two numbers.

<! DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>

</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<h3> Guru99 Global Event</h3>

<div ng-app = "mainApp" ng-controller = "DemoController">
    <p>Result: {{result}}</p>
</div>
<script>
    var mainApp = angular.module("mainApp", []);

    mainApp.service('AdditionService', function(){
        this.ADDITION = function(a,b) {
            return a+b;
        }
    });

    mainApp.controller('DemoController', function($scope, AdditionService) {

            $scope.result = AdditionService.ADDITION(5,6);
    });
</script>

</body>
</html>

In the above example, the following steps are carried out

  1.  mainApp.service('AdditionService', function() 

Here we are creating a new service called 'AdditionService' using the service parameter of our main AngularJS JS module.

  1.  this.Addition = function(a,b)

Here we are creating a new function called Addition within our service. This means that when AngularJS instantiates our AdditionService inside of our controller, we would then be able to access the 'Addition' function. In this function definition, we are saying that this function accepts two parameters, a and b.

  1.  return a+b; 

Here we are defining the body of our Addition function which simply adds the parameters and returns the added value.

  1.  mainApp.controller('DemoController', function($scope, AdditionService)

This is the main step which involves dependency injection. In our controller definition, we are now referencing our 'AdditionService' service. When AngularJS see's this, it will instantiate an object of type 'AdditionService.'

  1.  $scope.result = AdditionService.Addition(5,6);

We are now accessing the function 'Addition' which is defined in our service and assigning it to the $scope object of the controller.

So this is a simple example of how we can define our service and inject the functionality of that service inside of our controller.

Summary:

  • Dependency Injection as the name implies is the process of injecting dependent functionality into modules at run time.
  • Using dependency injection helps in having a more re-usable code. If you had common functionality that is used across multiple application modules, the best way is to define a central service with that functionality and then inject that service as a dependency in your application modules.
  • The value object of AngularJS can be used to inject simple JavaScript objects in your controller.
  • The service module can be used to define your custom services which can be re-used across multiple AngularJS modules.

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...