搬运官方文档相关介绍
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
翻译过来就是:
config 配置模块,得到在 提供者注册和配置 阶段执行。只能注入提供者和常量配置块。这是为了防止意外实例化的服务之前,他们已经完全配置。
run 运行模块,执行后创建了喷射器和用于启动应用程序。只能注入运行实例和常量。这是在应用程序运行时防止进一步的系统配置。
1、先看一个清单:
服务/阶段 | provider | factory | service | value | constant |
---|---|---|---|---|---|
config阶段 | Yes | No | No | No | Yes |
run 阶段 | Yes | Yes | Yes | Yes | Yes |
注意,provider 在config阶段,注入的时候需要 加上 provider 后缀 ,可以调用非 $get 返回的方法在 run 阶段注入的时候, 无需加 provider 后缀 ,只能调用 $get 返回的方法
2、ng的运行机制 config
阶段是给了ng上下文一个针对constant与provider修改其内部属性的一个阶段,而run
阶段是在config之后的在运行独立的代码块,通常写法runBlock简单的说一下就是ng启动阶段是 config-->run-->compile/link
执行顺序区别的demo:
var myApp=angular.module("exampleApp", ["exampleApp.Controllers", "exampleApp.Filters", "exampleApp.Services", "exampleApp.Directives"]);
myApp.constant("startTime", new Date().toLocaleString());
myApp.config(function(startTime){
console.log("Main module config: " + startTime);
});
myApp.run(function(startTime){
console.log("Main module run: " + startTime);
})
angular.module("exampleApp.Directives", [])
.directive("highlight", function($filter){
var dayFilter = $filter("dayName");
return function(scope, element, attrs){
if(dayFilter(scope.day) == attrs["highlight"]){
element.css("color", "red");
}
}
})
var now = new Date();
myApp.value("nowValue", now);
angular.module("exampleApp.Services", [])
.service("days", function(nowValue){
this.today=nowValue.getDay();
this.tomorrow=this.today + 1;
})
.config(function(){
console.log("Services module config: (no time)");
})
.run(function(startTime){
console.log("Services module run: " + startTime);
})
然后控制台输出结果:
都是最先执行config,然后是run。
而且这两个单词的意思就是配置、执行,符合常理。