Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 569
Ross Wilson Avatar asked Dec 20 '22 14:12

Ross Wilson


1 Answers

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')); });
like image 107
Hitmands Avatar answered Dec 24 '22 00:12

Hitmands