Angular Run Block - Use UI-Router $stateProvider to Resolve Promise

后端 未结 4 968
死守一世寂寞
死守一世寂寞 2020-12-11 06:33

UI-Router is different than Angular\'s ngRoute. It supports everything the normal ngRoute can do as well as many extra fu

4条回答
  •  时光说笑
    2020-12-11 07:33

    For adding resolve unconditionally to one or several states an abstract state should be used for inheritance:

    $stateProvider
    .state('root', {
        abstract: true,
        resolve: {
            common: ...
        },
    })
    .state('some', {
        parent: 'root',
        ...
    });
    

    It is the preferred method which requires no hacking.

    As for the equivalent of dynamic $route resolver in UI Router, here is a small problem. When a state is registered with state method, it is stored internally and prototypically inherited from the definition, rather than just being assigned to state storage.

    Though the definition can be acquired later with $state.get('stateName'), it is not the same object as the one which is being used by the router internally. Due to how JS inheritance works, it won't make a difference if resolve object exists in the state, so new resolver properties can be added there. But if there's no $state.get('stateName').resolve, that's dead end.

    The solution is to patch state method and add resolve object to all states, so resolver set can be modified later.

    angular.module('ui.router.hacked', ['ui.router'])
    .config(function ($stateProvider) {
      var stateOriginal = $stateProvider.state;
      $stateProvider.state = function (name, config) {
        config.resolve = config.resolve || {};
        return stateOriginal.apply(this, arguments);
      }
    })
    
    angular.module('app', ['ui.router.hacked']).run(function ($state) {
      var state = $state.get('some');
      state.resolve.someResolver = ...;
    });
    

    As any other hack, it may have pitfalls and tends to break. Though this one is very solid and simple, it requires additional unit-testing and shouldn't be used if conventional methods could be used instead.

提交回复
热议问题