Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs ui-router, How to get preload resolve value when $stateChangeSuccess trigger?

$stateProvider.state('home', {
  url: '/', 
  resolve: {
    person: function() { 
      return 'good' 
    } 
  }

like above state config, how can I get the 'person' value in $stateChangeSuccess callback function ?

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    // I want get the 'person' value in this function, what should I do?
});
like image 934
Duoduo Avatar asked Dec 12 '22 04:12

Duoduo


1 Answers

We had the same problem. We solved it by relying on some internal implementation details of ui-router; this does mean that it might break in a future version of angular, but here is the function we used:

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;
}

That will get the params, includes, and all the (resolved) resolve objects. We use that in the callback like so:

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

    var person = toState.resolve.person;
}

I hope that helps!

like image 94
taxilian Avatar answered Feb 12 '23 12:02

taxilian