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