How can I resolve data for all states with Angular UI Router?

angular-ui-router, angularjs, javascript

Solution

You could resolve the data you want for multiple ui-router states in a parent state. The child state would then have this data as well.

$stateProvider
.state('app', {
  url: "/",
  resolve: {
    authorizationCheck: function() {
       // Do your API checks or whatever
    }
  }
})
.state('app.somepage', {
  url: "/somepage",
  templateUrl: "partials/some.page.html",
  controller: function($scope) {

  }
})

It would make more sense to have authorization checks within a Service though, so you might want to inject an Auth service in the main controller, and base states and availability on that.

Problem

In my application every route requires that account data has been retrieved from my API prior to rendering. To accomplish this, I do the following using ngRoute: ``` $rootScope.$on('$routeChangeStart', function(event, next, current) { next.$$route.resolve = next.$$route.resolve || {}; next.$$route.resolve.authorizationCheck = function() { return deferredAccountData.promise; }; }); ``` So before each route, the `authorizationCheck` resolve, which returns a promise, must resolve. This works perfectly. I'm now switching to using UI Router, and I need to preserve this functionality. What are some options for accomplishing this? One option I can think of is using nested states and having all routes inherit resolves from a parent state. Though I'd prefer to not nest if possible. Are there any other options?

Original source