9

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?

Bunkered
  • 309
  • 1
  • 3
  • 12

2 Answers2

5

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

Community
  • 1
  • 1
Max
  • 8,671
  • 4
  • 33
  • 46
  • Thanks, I created I site config controller and used resolve to include it on all other controllers that needed it. All working, but I feel like there might be a better way of doing it. – Bunkered Nov 09 '12 at 14:39
  • 5
    What if the Controller is not attached to the route? – ya.teck Mar 31 '15 at 08:27
0

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;
          }
}
FlavorScape
  • 13,301
  • 12
  • 75
  • 117