AngularJS run service function before other functions

user1625066 picture user1625066 · May 21, 2014 · Viewed 12.6k times · Source

I am new to AngularJS and have a service that loads my initial user configuration

angular.module('myApp').service('myService', ['$http', function ($http) {
    var self = this;
    self.user = {};

    self.loadConfiguration = function () {
        $http.get('/UserConfig').then(function (result) {
            self.user = result.data;
        });
    };

    self.loadConfiguration();
}]);

I have a controller that uses the configuration from this service

angular.module('myApp').controller('myController', ['$scope', 'myService', function ($scope, myService) {
    var self = this;

    // calculation based on service value
    self.something = myService.user.something * something else;
}]);

The problem here is that myService.user.something may be undefined since the AJAX request may not have completed when this code is called. Is there a way to have the service complete before any other code is run? I want the service function 'loadConfiguration' to be run only once irrespective of the number of controllers that depend on it.

Answer

akn picture akn · May 21, 2014

You can call your service method inside .run() function

Run Blocks

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.

https://docs.angularjs.org/guide/module

angular.module('myApp').run(function()){
   //use your service here
}

One way to deal with ajax delay, is use $rootScope.$broadcast() function on $http.success which will broadcast your custom event to all controllers. Antoher way is to use promises and perform actions in controllers after resolve. Here are some ideas: https://groups.google.com/forum/#!topic/angular/qagzXXhS_VI/discussion