Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defer whole page load in AngularJS until service's ajax has finished

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.

like image 265
Dynalon Avatar asked Sep 02 '13 12:09

Dynalon


2 Answers

<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

like image 165
LauroSkr Avatar answered Nov 20 '22 03:11

LauroSkr


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

like image 1
ReadyBird Avatar answered Nov 20 '22 04:11

ReadyBird