Ross Wilson
Ross Wilson

Reputation: 129

Angular ui-router dynamically add resolve function to all states

I am trying to add a resolver function to every state within my application in order to wait for an application 'boot' process to complete. I have the following code already:

angular.forEach($state.get(), function(state) {
  state.resolve = state.resolve || {};
  state.resolve.session = function() {
    return SessionResolver.handle(state);
  }
});

SessionResolver is a service where the handle(state) function returns a promise that is resolved once the boot process is complete.

This works fine unless a state has been defined with no existing resolve object. For example, the following state will block until the SessionResolver.handle promise resolves:

$stateProvider.state('dashboard', {
  url: "/",
  templateUrl: "dashboard.html",
  controller: "DashboardCtrl",
  resolve: {}
});

But if the resolve object isn't set the state doesn't block:

$stateProvider.state('dashboard', {
  url: "/",
  templateUrl: "dashboard.html",
  controller: "DashboardCtrl",
});

I'd rather not add an empty resolve object to each of my states, since I might as well add the SessionResolver.handle resolve function to them all while I'm at it.

Any ideas why dynamically adding resolve functions to states fails unless the resolve object already exists?

Upvotes: 4

Views: 2058

Answers (2)

Hitmands
Hitmands

Reputation: 14169

I've solved the issue in this way:

angular.module('sample', ['ui.router']).config(function($stateProvider) {
   var $delegate = $stateProvider.state;

   $stateProvider.state = function(name, definition) {
      definition.resolve = angular.extend({}, definition.resolve, {
         myCustomResolve: function() { return true; }
      });

      return $delegate.apply(this, arguments);
   };
   $stateProvider.state('example', { url: 'example/' });

}).run(function($state) { console.log('have resolve?', $state.get('example')); });

Upvotes: 9

fshaw1
fshaw1

Reputation: 366

I may not completely understand the context for you issue, but it seems what you are looking for is an abstract state. You can declare a base abstract state for your app that all other states will be a child of, and add the resolve into that abstract state. That way all states will "block" until the parent resolve block is finished.

$stateProvider.state('parent', {
  abstract: true,
  template: '',
  resolve: {
    session: function() {
      return SessionResolver.handle(state);
    }
  }
}).state('parent.child1', {
  url: '/',
  template: 'dashboard.html',
  controller: 'DashboardController'
});

You can find more documentation about abstract states here https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#abstract-states.

Upvotes: 2

Related Questions