AngularJS runs a utility 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 is that myService.user.something may be undefined, because the AJAX request may not complete when this code is called. Is there any way to end the service before running any other code? I want the loadConfiguration service function to be run only once, regardless of the number of controllers that depend on it.

+8
angularjs angularjs-service
source share
2 answers

If you want your code in the controller to execute after an AJAX call, you can 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 bind an object to an event.

See https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope.

+5
source share

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

Run blocks

The start blocks are closest to Angular to the main method. A start block is the code that you need to run to run an expression. It runs after all services have been configured and the injector has been created. Typically, run blocks contain code that is difficult to test, and for this reason must be declared in isolated modules, so that they can be ignored in block tests.

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

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

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

+5
source share

All Articles