AngularJS: How to load json feed before app load?

All we need is an easy explanation of the problem, so here it is.

I’m just learning angularJS (using angular-seed) and I need to load my site config from a JSON feed before the rest of the site loads.

Unfortunately, using $http or $resource doesn’t return the feed in time for the rest of the app to load.

What is the correct way to force the app to load this data before the rest of the app?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You have to use the Controller.resolve method. Check out Misko’s (one of the core Angular developer) answer https://stackoverflow.com/a/11972028/726711

Method 2

Using the resolve method broke all my unit tests… I went with this way, where settings is a service.

$q.when(settings.loadConfig()).then(function () {
  console.log( settings.versionedApiUrl );  
});

Then, i check if we’ve already loaded settings to make sure we don’t request more than once.

class settings {
    loadConfig = ( ):angular.IPromise<any> =>  {

                var deferred = this.q.defer();

                if( this.settingsLoaded  ){
                      deferred.resolve({})
                      return deferred.promise;
                }

                this.http({
                      url:'config.json'
                }).then((result) => {

                      if( result.data ){
                            this.versionedApiUrl = result.data.versionedApiUrl;
                            this.apiServer = result.data.apiServer;
                            this.widgetServiceRoot = result.data.widgetServiceRoot;
                            this.settingsLoaded = true;
                      }

                      deferred.resolve({});
                });
                return deferred.promise;
          }
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply