AngularJS - 依賴注入



依賴注入是一種軟體設計模式,其中元件被賦予它們的依賴項,而不是在元件內部硬編碼。它使元件免於查詢依賴項,並使依賴項可配置。它還有助於使元件可重用、可維護和可測試。

AngularJS 提供了一種強大的依賴注入機制。它提供了以下核心元件,這些元件可以相互注入作為依賴項。

  • 值 (Value)
  • 工廠 (Factory)
  • 服務 (Service)
  • 提供者 (Provider)
  • 常量 (Constant)

值 (Value)

值是一個簡單的 JavaScript 物件,它用於在配置階段將值傳遞給控制器(配置階段是 AngularJS 自舉自身的時候)。

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

工廠 (Factory)

工廠是一個函式,用於返回值。它根據需要建立值,無論何時服務或控制器需要它。它通常使用工廠函式來計算和返回值。

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

服務 (Service)

服務是一個包含一組用於執行某些任務的函式的單例 JavaScript 物件。服務使用 service() 函式定義,然後注入到控制器中。

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

提供者 (Provider)

提供者由 AngularJS 在配置階段內部使用來建立服務、工廠等。以下指令碼可用於建立我們之前建立的 MathService。提供者是一種特殊的工廠方法,具有 get() 方法,用於返回值/服務/工廠。

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

常量 (Constant)

常量用於在配置階段傳遞值,考慮到值不能在配置階段使用。

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

示例

以下示例顯示了所有上述指令的使用:

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>

輸出

在 Web 瀏覽器中開啟 testAngularJS.htm 並檢視結果。

廣告