Reputation: 24799
tI know when the run
method gets invoked (after the injector is created) and that you can inject only instances, but I was wondering, what would you typically do/want in this method? What is the point of this method?
The documentation talks about a 'kickstart', what is meant by this?
Upvotes: 3
Views: 61
Reputation: 24676
Angular offers two functions which let you execute code during your modules initialization. First, mid-way through initialization config
is called. Then once Angular is done initializing it calls run
. So run
is often compared with the main function provided in many languages since it's the function that starts things off (kickoff meaning "start off" or "get running").
Thus, run
is called just once and executes before the rest of your code.(except after config
) Unlike config
it's called after the injector is created, as you noted, so you can inject any services/providers into it- and call functions they provide.
Note that because run
is called so early there is no scope other than rootScope so you can't inject in $scope
but you can inject $rootScope
. Because of this some use run
to setup global variables on $rootscope
(for good or for bad...)
From http://docs.angularjs.org/guide/module :
- 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.
Since run
is called before anything else it is sometimes used for authentication. Here's an example of doing that- you'll see config
is used to set up routing and then run
does some initialization including creating a watch
that must be established during initialization : http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/
So, run
or config
are good for one-time initialization especially when you want to ensure that initialization occurs before any of your other code runs.
Upvotes: 2