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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
What if the Controller is not attached to the route?
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;
          }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.