Reputation: 1426
If you inject service/factory inside the run function as dependency means it executes priority from normal order. It means service/factory runs before directive setup. Normal order is
My question is why we used to inject service in run function? What is the benefit?
Upvotes: 0
Views: 357
Reputation: 806
The benefit could be with ui-router or other stateRouter. Here is the code example:
.run(function ($rootScope, krozAuthService) {
$rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams){
if (krozAuthService.roleAccess[state] &&
krozAuthService.roleAccess[state] === 'DISABLED'){
e.preventDefault();
return;
}
This is from authentication part of application which was wrote by me. krozAuth is the service for authentication and it have information about role of currently logged in user. So, logged in user WILL NOT be able to go to the state and HTML page WILL NOT be loaded in case of user have no rights for that.
Upvotes: 2
Reputation: 1395
From AngularJS docs:
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
Most examples available on the internet mention Authentication as one of it's main uses.
Upvotes: 0