2

I've been searching for an answer for this but haven't got any unambiguous or clear answer on how to solve and come about this.

In my anguarJS app, I want to make sure that the very first thing after AngularJS has been loaded / bootstrapped, it goes to the server via $http and fetch some settings (by called the api: /api/settings/get) - depending on the subdomain and/or if there is a JWT or other user-session it will retrieve some setting data which should be added to the $rootScope.

My problem has been that I haven't been able to "halt" the app and only continue it's everyday life when and only when the settings has been fetched and populated the $rootScope. If the fetch or settings call might fall the app should "stop" - so it's crucial that these settings is loaded very early so I know that everything (services, controllers, directives, etc.) has access to them.

I've tried with $broadcast event and put it into my .run function in angular but it seems to still resolve the app (perhaps obviously because it's async).

apiConnector.get('api/settings/get').then(function(settings) {
  $rootScope.settings = settings;
  $rootScope.$broadcast('settings-fetched');
});

However, I don't like this approach and requires me to listen for this event everywhere.

My routes are both public and restricted.

I hope someone can help me in the right direction of how I would solve this.

Rob
  • 14,746
  • 28
  • 47
  • 65
Emil Devantie Brockdorff
  • 4,724
  • 12
  • 59
  • 76

1 Answers1

0

Since you're using ui-router I suggest using resolve before entering your default state: https://github.com/angular-ui/ui-router/wiki#resolve

Example route configuration from the ui-router docs:

$stateProvider.state('myState', {
      resolve:{
         // Example using function with returned promise.
         // This is the typical use case of resolve.
         // You need to inject any services that you are
         // using, e.g. apiConnector in this example
         settingsObj:  function(apiConnector){
            return apiConnector.get('api/settings/get');
         }
}

If this get fails you can handle this in the resolve by using .then() to redirect user away from app or w/e. As with usual promises in angular.

Erik Svedin
  • 1,286
  • 12
  • 26