javascript - 为什么以及在 Angular 中使用 App.run()

标签 javascript angularjs

所以在大多数情况下,我看到 angular.module('', []).run() 没有被使用。这是否意味着 Angular 在内部调用它?

如果使用为什么?如果可能,请提供一个简单的用例,让我了解该功能的必要性。

最佳答案

这是the official docs say :

A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consists of a collection of two kinds of blocks:

  • 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.

因此,AngularJS 有两个主要阶段来引导每个拆分为两个子阶段:

  • 配置
  • “正在运行”

  • 编译&绑定(bind)
  • 第一个摘要周期

您可以订阅其中的每一个。要订阅 run 阶段,您可以使用模块的 run 方法。此阶段可用于在 AngularJS 解析 DOM 和编译组件之前以及在第一个更改检测周期之前执行一些逻辑。

例如,您可以在将服务注入(inject)任何组件之前对其进行初始化:

angular.module('mymodule').run(function (MyService) {
    MyService.init();
});

如果你不订阅 run 阶段,AngularJS 不会做任何特别的事情。根本不会触发任何功能。

关于javascript - 为什么以及在 Angular 中使用 App.run(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661081/

相关文章:

javascript - 回调可以定义参数吗?

javascript - 加载微调器不适用于 Angularjs 中的 ng-click 或 ng-change

angularjs - Angular $timeout - TypeError : object is not a function

javascript - 模拟服务时 Jasmine 出现问题

php - REST PUT 请求返回 GET 500 错误,这是否合理?

javascript - 生态错误消息 : Unexpected 'INDENT' in Windows

javascript - 从指令触发 View 的 Controller 功能

angularjs - 当 ng-checked 值为 False 时启用复选框?

javascript - jquery排序中如何让空数据排在最后

jquery - 如何在选择框上显示垂直滚动条