×

Dependency Injection in Angular 8

Dependency injection (DI), is an essential application design pattern. Angular 8 has its own DI framework, which used in the design of Angular application to increase efficiency and portability.

Dependencies are the services that a class needs to perform its function. DI is a coding pattern in which a class asks for dependencies from external sources rather than creating itself.

In Angular, the DI framework provides dependency to the class when that class is instantiated. We can use it to make our apps flexible, efficient, robust, and testable.

Dependency Injection (DI) is a software design pattern that deals with how component gets its dependencies.

The AngularJS injector subsystem is used to creating components, resolving its dependencies, and providing them to other components as requested.

Why Dependency Injection?

  • Angular dependency injections make an application modularize.
  • Angular DI makes it easier to reuse components an application.
  • It makes it easier to test the components of an application.
  • It makes it easier to configure components of an application.

Components of Dependency Injection in Angular 8

  • Provider
  • Factory
  • Service
  • Constant
  • Value

 1.Value

Value is an object. It can a number, string or javascript object. Value is used to pass the value to controller, services or factories in config or run phase.Value() function is used in module to define values. It consists of two parameters, the first is assigned value.

 var demo = angular.module("myModule", []); //define the module
 demo.value("NumberAsValue", 101); //create a value object and pass in the data.
 demo.value("stringAsValue", "tutorial");
 demo.value("objectAsValue", { val1 : 103, val2 : "xyz"} ); 

2.Service

It is like a singleton JavaScript object. It consists of a set of functions to execute any certain tasks. Service() function is used in a module to create services. After the creation, it is used into the 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>
  
  
<div ng-app = "serviceApp" ng-controller = "serviceController">
  <p>Result: {{result}}</p>
</div>
<script>
  var t = angular.module("serviceApp", []);
  
t.service('sum', function(){
  this.addition = function(x,y) {
    return x+y;
   } 
 });
  
t.controller('serviceController', function($scope, sum) {
    $scope.result = sum.addition(5,6);
});
   </script> 
   </body> 
</html> 

3.Constant

It is used to pass a value at config phase irrespective of the fact that value cannot be moved during its config phase.

4.Provider

In the configuration phase, factory and services are created by using a provider.

5.Factory

A factory is a function that returns the value on demand. It returns value based on the requirement made by service and controller.

It uses a factory function to process the value and return the output.

Angular Dependency Injection Example-

 <!DOCTYPE html> 
<html> 
 <head> 
    <title>AngularJS Dependency Injection</title> 
</head> 
<body> 
<div ng-app = "myApp" ng-controller = "myController"> 
 <p>Enter a number: <input type = "number" ng-model = "number" /></p> 
 <button ng-click = "square()">Result</button> 
 <p>Result: {{result}}</p> 
</div> 
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script> 
 var demo = angular.module("myApp", []); 
 demo.config(function($provide) { 
   $provide.provider('MathService', function() { 
     this.$get = function() { 
        var factory = {}; 
        factory.sum = function(a, b) { 
          return a + b; 
        }  
        return factory; 
      };  
    });  
 });  
 demo.value("defaultInput", 10); 
 demo.factory('MathService', function() { 
   var factory = {}; 
  
    factory.sum = function(a, b) { 
     return a + b; 
   }  
    return factory; 
 });  
  demo.service('demoService', function(MathService){ 
  this.addition = function(a) { 
     return MathService.sum(a,a); 
   }  
 });  
   demo.controller('myController', function($scope, 
 demoService, defaultInput) { 
   $scope.number = defaultInput; 
   $scope.result = demoService.addition($scope.number); 
 
   $scope.addition = function() { 
   $scope.result = demoService.addition($scope.number); 
   }  
 }); 
    </script>  
 </body>  
</html> <!DOCTYPE html>  
<html>
  <head>
     <title>AngularJS Dependency Injection</title>  
  </head>  
  <body> 
 <div ng-app = "myApp" ng-controller = "myController">
        <p>Enter a number: <input type = "number" ng-model = "number" /></p>
        <button ng-click = "square()">Result</button>
        <p>Result: {{result}}</p>
     </div> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script> 
 <script>
        var demo = angular.module("myApp", []); 
demo.config(function($provide) {
           $provide.provider('MathService', function() {
              this.$get = function() {  
                 var factory = {}; 
 factory.sum = function(a, b) {
                    return a + b;  
                 }  
                 return factory;  
              };  
           });  
        }); 
demo.value("defaultInput", 10); 
 demo.factory('MathService', function() {
           var factory = {}; 
       factory.sum = function(a, b) {
              return a + b;  
           }  
           return factory;  
        });  
   demo.service('demoService', function(MathService){
           this.addition = function(a) {
              return MathService.sum(a,a);
           }  
        });  
  
        demo.controller('myController', function($scope, demoService, defaultInput) {
           $scope.number = defaultInput;
           $scope.result = demoService.addition($scope.number);
            $scope.addition = function() {
              $scope.result = demoService.addition($scope.number);
           }  
        });  
         </script>  
     </body>  
</html> 

Output:

Enter a Number:20

Result

Result:40

Why we use dependency injection?

Angular 8 Dependency Annotation

Some functions like as controller, service, and factories are implore  through the injector in Angular 8. Therefore, it is required to annotate those functions, so that injector will be well aware of which functions, so that injector will be well aware of which functions is to be injected.

Angular provides three way to annotating code. It is provided with a service name.

1.Inline Array Annotation

Inline array annotation is mostly used to annotate components in angular.

var demoApp = angular.module("myApp", []);
demoApp.controller("MyController", ["$scope", "MyService", function($scope, MyService) {
    $scope.myService = MyService;
}]); 

In the example, an array is used. The elements of an array are the dependencies and the string type followed by a function.

2. $inject Property Annotation

It is an array of dependency that is being injected in the function. We can use the $inject property only when it is allowed to rename the function parameter in our code and still to inject the right services.

var demo app = angular.module("myApp", []);
var MyController = function($scope, MyService) {
   $scope.myService = MyService;
};
MyController.$inject = ["$scope", "MyService"];
demoApp.controller("MyController", MyController); 

it is an array of dependency name, therefore, synchronization is necessary between the array and the parameters into the function declaration.

3.Implicit Annotation

It is the easiest way. But if we are minifying code then we cannot use implicit annotation. The parameter passed inside a function are treated as the name of services.

 var demoApp = angular.module("myApp", []);
demoApp.controller("MyController", function($scope, MyService) {
   $scope.myService = MyService;
}); 


Strict Dependency Injection in Angular 8

 <!doctype html>
<html ng-app="demoApp" ng-strict-di>
<body>
 Result of 5+5 is: {{5+5}}
 <script src="angular.js"></script>
</body>
</html> 

We are opt for strict dependency injection in Angular by using the ng-strict-di directive. It will apply on the same elememt as ng-app. When we use strict mode, it will throw an error.

Output

Result of 5+5:10


Related Topics

Angular 8 NgStyle Directive

Angular 8 NgStyle Directive The ngStyle attribute is used to change and style the multiple properties of Angular. We can change the value, color, and size, etc. of the component. It is a built-in...

1 minute read.

Dependency Injection in Angular 8

Dependency injection (DI), is an essential application design pattern. Angular 8 has its own DI framework, which used in the design of Angular application to increase efficiency and portability. Dependencies are the services that...

7 minutes read.

Difference between Angular and React

Difference between Angular and React Parameters AngularReactType Angular is a complete framework. React is a JavaScript library, and much older compared...

2 minutes read.

Dynamic components in Angular 8

Dynamic components in Angular 8 The dynamic component is one of the versatile and core concept introduced in Angular, Component template is not fixed. An application needs to load new elements...

4 minutes read.

Angular 8 Animation

What is Animation? The animation is a process of drawing, designing, making layouts, and preparation of photographic sequences which are integrated into the multimedia and gaming products. A reflection of movement created for displaying...

5 minutes read.

Angular 8 ngIf Directive

ngIf Directive is the part of structural directives.The NgIf is the most straightforward structural Directive and comfortable to understand. The ngIf Directives is used to add and remove HTML elements according to...

2 minutes read.

Angular 8 App Loading

How an Angular 8 app loaded and started When we create an Angular app and run it by using ng serve command, it looks like the below screenshot. It is a simple...

3 minutes read.

Angular 8 *ngFor Directive

Angular 8ngFor Directive The *ngFor directive is used to repeat to repeat a portion of HTML template once per each item from an iterable list (collection). The ngFor is an Angular...

2 minutes read.

Difference between Node.js and ASP.net

Introduction to Node.js V8 (the JavaScript engine operating inside Google Chrome) is packaged with certain libraries and is mostly used for input & output, which includes creating data and managing connection...

4 minutes read.

Scalability and Validation Forms in Angular 8

Form Validation Validation is an essential part of managing any set of forms. If we are checking for required fields or querying an external API for a username. Angular 8 provides a set of...

1 minute read.

Deployment of an Angular 8 app

Deploying an Angular 8 app To implement our application, we have to compile it and then host the JavaScript, CSS, and HTML on a web server. Build an Angular application which is very portable...

4 minutes read.

Angular 8 Components

Angular is used for building mobile and desktop web applications. The component is the basic building block of Angular. It has a selector, template, style, and other properties, and it...

4 minutes read.

Creating first APP in Angular 8

Firstly, we have to open Git Bash and, then we have to write the following command in it. ng new my -app The project has been created now so that now we have to go...

2 minutes read.

Angular 8 Libraries

Angular libraries are built a solution of general problems like presenting a unified user interface, presenting data, and allowing the data entry. Developers can create standard solutions for particular domains...

3 minutes read.

String Interpolation in Angular 8

String Interpolation in Angular 8 String interpolation is a one-way data-binding technique which is used to output the data from a typescript code to HTML template. It uses the template expression. It uses the...

2 minutes read.

Routing in Angular 8

Routing Angular Router is a powerful JavaScript router is built and maintained by the Angular core team that can install from the package @angular/router. Routing provides a complete routing library with the possibility of multiple...

4 minutes read.

Angular CLI Commands

All CLI commands of Angular Angular CLI is a command-line interface which is used to initialize, develop, and maintain Angular applications. We can use these Command on command prompt or consequentially by an associated...

8 minutes read.

ngSwitch Directive in Angular 8

Angular 8 ng-Switch Directive The ng-Switch Directive hides and shows the HTML elements depending on an expression. Child elements with the ng-switch-when directive will be displayed if it gets a match; otherwise, the component and...

2 minutes read.

How to create a Todo List App in Angular 7

What is a Todo List App? Todo List app is an app where users can add various tasks that they want to perform and have an idea of every task. If...

4 minutes read.

Express.js app.get() Request Function

Express.js Express is a flexible online application framework for Node.js that offers a strong set of functionality for both web and mobile applications. While preserving the familiar and adored Node.js features,...

4 minutes read.