Why and where App.run() is used in Angular

时间:2017-08-13 13:52:13

标签: javascript angularjs

So in most instances, I see angular.module('', []).run() not being used. Does that mean angular calls it internally?

If used why? If possible please provide a simple use case for me to understand the necessity of the function.

1 个答案:

答案 0 :(得分:3)

Here is what 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.

So AngularJS has two main stages of bootstrapping each split in two sub stages:

  • configuration
  • "running"

  • compilation & binding
  • first digest cycle

You can subscribe to each of them. To subscribe to the run phase you use run method of the module. This phase can be used to perform some logic before AngularJS parses the DOM and compiles components and before first change detection cycle.

For example, you can initialize a service before it's injected in any component:

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

If you don't subscribe to the run phase, AngularJS doesn't do anything special. Simply no function is triggered.