简体   繁体   中英

Fetch server settings after boostrap but before anything else

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM