Search code examples
angularjsangularjs-service

AngularJS run service function before other functions


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.


Solution

  • If you want to make sure that your code in controller gets executed after your AJAX call returns, you may use events.

    Use this in your service:

    angular.module('myApp').service('myService', ['$http', '$rootScope', function ($http, $rootScope) {
        var self = this;
        self.user = {};
    
        self.loadConfiguration = function () {
            $http.get('/UserConfig').then(function (result) {
                self.user = result.data;
                $rootScope.$broadcast('myService:getUserConfigSuccess');
            });
        };
    
        self.loadConfiguration();
    }]);
    

    In your controller:

    angular.module('myApp').controller('myController', ['$scope', 'myService', function ($scope, myService) {
        var self = this;
    
        $scope.$on('myService:getUserConfigSuccess', function() {
            // calculation based on service value
            self.something = myService.user.something * something else;
        })
    }]);
    

    You can even attach an object to the event.

    Please refer to https://docs.angularjs.org/api/ng/type/$rootScope.Scope .