Growler Growler - 6 months ago 36
AngularJS Question

Sequential Angular stateProvider resolves

I need to perform router resolves in order. Meaning first run

ProfileLoaded
http call, when that finishes, run
Access
resolve. How can I do this?

$stateProvider.
state('sign-up', {
url : '/sign-up',
templateUrl: '/html/pages/registration.html',
controller: 'signupCtrl',
resolve : {
// Load profile first, then check if they are subscribed
ProfileLoaded : ['$rootScope', function ($rootScope) {
return $rootScope.loadProfile();
}],
// Then check Access
access: ['Access', function (Access) {
return Access.isSubscribed();
}]
}
})


Where
$rootScope.loadProfile();
is an AJAX
$http
request and, where
Access.isSubscribed
relies on the loaded profile to perform auth'ed routing.

The logical choice would be to put
access
as a callback in
loadProfile
, but don't want it to get messy.

Answer

Assuming $rootScope.loadProfile returns a promise, simply add the required resolve property as a dependency, eg

access: ['Access', 'ProfileLoaded', function(Access, ProfileLoaded) {
    return Access.isSubscribed();
}]

See http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.$resolve#methods_resolve

Dependencies of invocables are resolved (in this order of precedence)

  • from the specified locals
  • from another invocable that is part of this $resolve call
  • from an invocable that is inherited from a parent call to $resolve (or recursively from any ancestor $resolve of that parent).

and

Invocables are invoked eagerly as soon as all dependencies are available.