Angularjs ui-router,$ stateChangeSuccess触发时如何获取预加载解析值?

Duo*_*duo 4 javascript resolve angularjs angular-ui-router

$stateProvider.state('home', {
  url: '/', 
  resolve: {
    person: function() { 
      return 'good' 
    } 
  }
Run Code Online (Sandbox Code Playgroud)

像上面的状态配置一样,如何在$ stateChangeSuccess回调函数中获取'person'值?

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    // I want get the 'person' value in this function, what should I do?
});
Run Code Online (Sandbox Code Playgroud)

tax*_*ian 13

我们遇到了同样的问题.我们依靠ui-router的一些内部实现细节来解决它; 这确实意味着它可能会在未来的angular版本中破坏,但这是我们使用的函数:

function annotatedStateObject(state, $current) {
    state = _.extend({}, state);
    var resolveData = $current.locals.resolve.$$values;
    state.params = resolveData.$stateParams;
    state.resolve = _.omit(resolveData, '$stateParams');
    state.includes = $current.includes;
    return state;
}
Run Code Online (Sandbox Code Playgroud)

这将获得params,includes和所有(已解决的)解析对象.我们在回调中使用它,如下所示:

$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
    toState = annotatedStateObject(toState, $state.$current);

    var person = toState.resolve.person;
}
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助!