angularjs中config和run的区别

搬运官方文档相关介绍

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。
而且这两个单词的意思就是配置、执行,符合常理。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,973评论 6 342
  • 大家好,我是IT修真院深圳分院第01期学员,一枚正直善良的web程序员。 今天给大家分享一下,修真院官网 JS任务...
    长天_阅读 1,367评论 0 4
  • 1. 介绍 AngularJS是一款由Google公司开发维护的前端MVC框架,其克服了HTML在构建应用上的诸多...
    崔皓翔阅读 862评论 0 5
  • 擦肩而过的瞬间 我侧身走过 无意的我看见你的身影 心里的一震 从未有过的感觉 我敢肯定 你就是我要找的那个她 从此...
    普安阅读 190评论 0 2