AngularJS - 依赖注入


依赖注入是一种软件设计,其中组件被赋予其依赖关系,而不是在组件内对它们进行硬编码。它使组件免于定位依赖项并使依赖项可配置。它还有助于使组件可重用、可维护和可测试。

AngularJS 提供了一种至高无上的依赖注入机制。它提供了以下核心组件,这些组件可以作为依赖项相互注入。

  • 价值
  • 工厂
  • 服务
  • 提供者
  • 持续的

价值

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

工厂

工厂是一个用于返回值的函数。每当服务或控制器需要时,它就会按需创造价值。它一般使用工厂函数来计算并返回值。

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

服务

服务是一个单例 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);
   }
});

提供者

AngularJS 内部使用 Provider 在配置阶段创建服务、工厂等。以下脚本可用于创建我们之前创建的 MathService。Provider 是一个特殊的工厂方法,具有 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;
      };
   });
});

持续的

考虑到在配置阶段不能使用值的事实,常量用于在配置阶段传递值。

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并查看结果。