×

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

Data flow forms in Angular 8

When we are building forms in Angular, it is essential to understand how the framework handles data flowing from the user or programmatic changes. Reactive and template-driven forms follow two different strategies when...

3 minutes read.

Angular 8 Observables

Observables provide support for passing messages between publisher and subscription in our application. The observables can deliver the multiple values of any type like literal, messages, depending on the content. It is an...

6 minutes read.

Installation of Angular 8

Installation Guides to Angular 8 step by Step Angular combines declarative templates, dependency injection and, end to end tooling to solve development challenges. Angular empowers developers to build an application that lives on the...

4 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 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.

Angular 8 Conclusion

Angular version 8 looks like a more accessible solution entirely focused on the modern technological trends added features. Like Ivy, route configurations use dynamic imports, builder APIs in the CLI, web worker support,...

2 minutes read.

Angular 8 Tutorial

What is Angular 8 Angular is a Framework of JavaScript used to build web and mobile applications. Angular 8 is a client-side TypeScript based structure which is used to create dynamic...

6 minutes read.

Event Binding in Angular 8

Event binding in Angular 8 Event binding is a data-binding from an element to a component. User actions such as keystrokes, mouse movement, clicks, and touches can be bound to the component property...

1 minute 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 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.

Angular 8 Module

Angular 8 Module It is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure the $injector. The module is a container of the different parts of an application....

6 minutes read.

Angular 8 ngClass Directive

Angular 8 ngClass Directive ngClass Directive is a type of attribute directive. Angular provided built-in directive, and it helps in adding or removing CSS classes on an HTML element. The ngClass directive allows...

2 minutes read.

Angular 8 Error Fixing

We can get errors in Angular because of many causes. Let's see an example to see some specific types of errors. We have to create an app with the name "testing-app." In this app,...

4 minutes read.

What is AOT and JIT Compiler in Angular

A program written in a high-level language is translated into machine code or a low-level language by a piece of software called a compiler. HTML templates are the primary building...

3 minutes read.

Two-way Data Binding in Angular 8

Two-way Data Binding in Angular 8 Two-way data binding is a synchronization between the model and the view. We can use the ngModel directive in two-way data binding. Custom two-way data binding is useful...

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.

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 Unit Testing

What is unit testing? Unit testing is a type of software testing where individual components of the software are tested. It is done during the development of any application. A unit may be...

6 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.

Angular 8 File Structure

File Structure in Angular 8: A file structure contains the files for one or more projects. A project is the set of files that comprise an application on a shareable...

3 minutes read.