AngularJS - Tiêm phụ thuộc

Dependency Injection là một thiết kế phần mềm trong đó các thành phần được cung cấp các thành phần phụ thuộc của chúng thay vì mã hóa chúng trong thành phần. Nó giải phóng một thành phần khỏi việc xác định vị trí phụ thuộc và làm cho các phụ thuộc có thể định cấu hình. Nó cũng giúp làm cho các thành phần có thể tái sử dụng, có thể bảo trì và kiểm tra được.

AngularJS cung cấp cơ chế tiêm phụ thuộc tối cao. Nó cung cấp các thành phần cốt lõi sau đây có thể được tiêm vào nhau dưới dạng phụ thuộc.

  • Value
  • Factory
  • Service
  • Provider
  • Constant

Giá trị

Giá trị là một đối tượng JavaScript đơn giản, được yêu cầu để chuyển các giá trị cho bộ điều khiển trong giai đoạn cấu hình (giai đoạn cấu hình là khi AngularJS tự khởi động).

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

//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...

//inject the value in the controller using its name "defaultInput"
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);
   }
});

Nhà máy

Factory là một hàm được sử dụng để trả về giá trị. Nó tạo ra giá trị theo yêu cầu bất cứ khi nào dịch vụ hoặc bộ điều khiển yêu cầu. Nó thường sử dụng một hàm gốc để tính toán và trả về giá trị.

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

//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   return factory;
}); 

//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});
...

Dịch vụ

Dịch vụ là một đối tượng JavaScript đơn chứa một tập hợp các chức năng để thực hiện các tác vụ nhất định. Dịch vụ được định nghĩa bằng cách sử dụng hàm service () và sau đó nó được đưa vào bộ điều khiển.

//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);
   }
});

Các nhà cung cấp

Nhà cung cấp được AngularJS sử dụng nội bộ để tạo dịch vụ, nhà máy, v.v. trong giai đoạn cấu hình. Tập lệnh sau có thể được sử dụng để tạo MathService mà chúng tôi đã tạo trước đó. Provider là một phương thức factory đặc biệt với phương thức get () được sử dụng để trả về giá trị / dịch vụ / nhà máy.

//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;
      };
   });
});

Không thay đổi

Hằng số được sử dụng để chuyển các giá trị ở giai đoạn cấu hình vì thực tế là giá trị không thể được sử dụng trong giai đoạn cấu hình.

mainApp.constant("configParam", "constant value");

Thí dụ

Ví dụ sau cho thấy việc sử dụng tất cả các lệnh được đề cập ở trên -

testAngularJS.htm

<html>
   <head>
      <title>AngularJS Dependency Injection</title>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <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 = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/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", 5);
         
         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>

Đầu ra

Mở testAngularJS.htm trong trình duyệt web và xem kết quả.