探究Angular依赖注入对象$injector

2022-11-06,,,,

$injector其实是一个IOC容器,包含了很多我们通过.module()和$provide创建的模块和服务。$injector服务提供了对依赖注入对象的访问,当然我们也可以调用angular.injector()来获得注入器。

var injector1 = angular.injector(["myModule","herModule"]); //获得myModule和herModule模块下的注入器实例

angular.injector()可以调用多次,每次都返回新建的injector对象,所以我们自己创建的myInjector和angular自动创建的$injector不是同一个对象。

    var injector1 = angular.injector(["myModule","herModule"]);
var injector2 = angular.injector(["myModule","herModule"]); alert(injector1 == injector2);//false

$injector常用的方法

通过$injector.get('serviceName')根据名字获得服务的实例,通过$injector.annotate('xxx')获得xxx的所有依赖项。

var app = angular.module("myApp",[]);
app.factory("hello1",function(){
return {
hello:function(){
console.log("hello1 service");
}
}
});
app.factory("hello2",function(){
return {
hello:function(){
console.log("hello2 service");
}
}
}); var $injector = angular.injector(['myApp']);
console.log(angular.equals($injector.get('$injector'),$injector));//true
var myCtrl2 = function($scope,hello1,hello2){
$scope.hello = function(){
hello1.hello();
hello2.hello();
}
}
myCtrl2.$injector = ['hello1','hello2'];
app.controller("myCtrl2", myCtrl2);
console.log($injector.annotate(myCtrl2));//["$scope","hello1","hello2"]

angular中三种声明依赖的方式

在我们使用.controller()函数的时候,会调用$controller服务,而在底层,则将使用$injector服务的invoke()函数创建该控制器,函数invoke()将负责分析什么参数需要被传入controller中,并执行该函数,所以底层实际上是使用了以下三种方式声明依赖。

    // 创建myModule模块、注册服务
var myModule = angular.module('myModule', []);
myModule.service('myService', function() {
this.my = 0;
}); // 获取injector
var injector = angular.injector(["myModule"]); // 第一种inference(推断)
injector.invoke(function(myService){alert(myService.my);}); // 第二种annotation (注入)
function explicit(serviceA) {alert(serviceA.my);};
explicit.$inject = ['myService'];
injector.invoke(explicit); // 第三种inline (内联)
injector.invoke(['myService', function(serviceA){alert(serviceA.my);}]);

$scope对象

因为$scope是局部的,不是一个服务,所以Angular使用它的方式和服务的方式不同,为了正确注入$scope变量,下面是一个理论上实践:

 $injector.invoke(function ($scope, $http) {
//在这里使用$scope,$http
},
null,
{$scope: {}});

$rootScope对象

$rootScope是由angularJS加载模块的时候自动创建的,每个模块只会有1个rootScope。rootScope创建好会以服务的形式加入到 $injector中。也就是说通过 $injector.get("$ rootScope ")能够获取到某个模块的根作用域。

// 新建一个模块
var module = angular.module("app",[]); // true说明$rootScope确实以服务的形式包含在模块的injector中
var hasNgInjector = angular.injector(['app','ng']);
console.log("has $rootScope=" + hasNgInjector.has("$rootScope"));//true // 获取模块相应的injector对象,不获取ng模块中的服务
// 不依赖于ng模块,无法获取$rootScope服务
var noNgInjector = angular.injector(['app']);
console.log("no $rootScope=" + noNgInjector.has("$rootScope"));//false // 获取angular核心的ng模块
var ngInjector = angular.injector(['ng']);
console.log("ng $rootScope=" + ngInjector.has("$rootScope"));//true

参考链接:

http://www.tuicool.com/articles/nUzMz2J

http://blog.csdn.net/aitangyong/article/details/39937505

http://www.jb51.net/article/92624.htm

探究Angular依赖注入对象$injector的相关教程结束。

《探究Angular依赖注入对象$injector.doc》

下载本文的Word格式文档,以方便收藏与打印。