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

广告