I have a single configService
in my AngularJS project that fetches some configuration values of the whole project from the server via an ajax request, i.e. like whether or not user's need to be moderated before their account is activated.
To display information according to the configuration, the whole first page load should be deferred until this ajax request completed. My service looks like:
angular.module('clientApp').factory('configService', function ($http) {
var configService = {};
var conf = {};
Object.defineProperty(configService, 'serverConfig', {
get: function () {
return conf;
}
});
$http.get('/api/config').success(function (data) {
conf = $.extend(conf, data);
});
return configService;
});
So, since the service is a singleton, this will only be executed one time when the page loads, not on every route change.
Now I know how to use $q
and promises, but my problem is how can defer the execution of ALL of angular until this service has finished its request? Most of my views will require values from configService.serverConfig
and depend on it for specific behaviour - doing this asynchronously and have a defered.then()
in every controller does not seem like the best idea.
<html ng-app="yourApp">
angular.element(document).ready(function() {
angular.bootstrap(document, ["yourApp"]);
});
maybe bootstrapping app manually can help...?
if that is not the case,then check this post ! Delaying AngularJS route change until model loaded to prevent flicker
I have written an angular module which emits a rootScope 'ajaxComplete' event once all initial ajax requests have been completed.
It uses an angular interceptor which resets a timer when new request are send, and also tracks the number of pending requests. Then considers the initial ajax requests completed once all responses return and no new requests are sent for 500 milliseconds. There is an example in the git project.
Happy coding.
https://github.com/jcarras/angular-ajax-complete
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With