3

I have an AngularJS application and inside the .run function, I get my site's settings from the server and add them to the root scope.

.run(function ($rootScope, SettingResource) {
    // Get the site settings (could be done in app controller?)
    $rootScope.SiteSettings = SettingResource.get();
});

I will need to access those settings in other controllers. How can I wait for that to be ready before the other controllers start loading?

Just for reference, here is the resource service:

function settingFactory($resource) {
    return $resource('/api/settings', {id: '@id'}, {'update': {'method': 'PUT'}});
}
Sean
  • 1,758
  • 3
  • 20
  • 34
  • Can you get the settings using AJAX, then call `.run` once the AJAX call finishes? – Max May 06 '16 at 16:03
  • 1
    Use a promise and have the controller resolve it. Or use a timeout in the controller waiting for the value to not be null. – Matthew Green May 06 '16 at 16:04
  • 2
    I am sure the .run block with run async so you wont be able to wait on the get request. Just use some evil jQuery or a vanilla XMLhttp request to preform the get request assign that stuff to the window and then manually bootstrap the angular app. Then in the .run block assign the stuff from the window into your $rootScopea and your controllers will have access to the data when they are instantiated. – rtn May 06 '16 at 16:07
  • 1
    Don't use jQuery. If you're using Angular, use $http. – Chris Stanley May 06 '16 at 16:28
  • How can I use $http before bootstrapping the application? – Sean May 06 '16 at 17:49

2 Answers2

0

Seems likes you should be able to use $q.all here, although I've never tried it myself.

Something like:

.run(function ($rootScope, SettingResource) {
    $q.all(SettingResource.get().then(function(data) {
        rootScope.SiteSettings = data;
        console.log("ok, I'm done here.")
     });    
});

Not that if SettingsResource is based on $resource, it doesn't return promises in the same way as a straight call to $http.get does. Check out this answer for what I think is a similar scenario with more details: Angular Resource calls and $q

Community
  • 1
  • 1
Mike Feltman
  • 5,160
  • 1
  • 17
  • 38
  • This wasn't working for me. It still had the same issues. I think a manual bootstrap might be the best option. – Sean May 06 '16 at 17:49
  • Did it error, or just not wait for the promise to resolve? – Mike Feltman May 06 '16 at 17:50
  • No error, it's just occasionally when refreshing the page, sometimes it wasn't resolved fast enough for the rest of the page. – Sean May 06 '16 at 17:55
0

i guess currently angular doesn't support an easy way to do so, you can find a discussion in here:

https://github.com/angular/angular.js/issues/4003

L.E.
  • 170
  • 2
  • 8