Angular ui-router动态地将解析函数添加到所有状态

Ros*_*son 4 javascript angularjs angular-ui-router

我正在尝试向我的应用程序中的每个状态添加一个解析器函数,以便等待应用程序的"启动"过程完成.我已经有以下代码:

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

SessionResolver是一个服务,其中handle(state)函数返回一个在启动过程完成后解析的promise.

除非定义了没有现有resolve对象的状态,否则这样可以正常工作.例如,以下状态将阻塞,直到SessionResolver.handle承诺解析:

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

但是如果未设置resolve对象,则状态不会阻塞:

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

我宁愿不resolve向我的每个状态添加一个空对象,因为我也可以在它处理时将SessionResolver.handle解析函数添加到它们.

除非解析对象已经存在,否则任何想法为什么动态地将解析函数添加到状

Hit*_*nds 7

我用这种方式解决了这个问题:

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')); });
Run Code Online (Sandbox Code Playgroud)