Duoduo
Duoduo

Reputation: 509

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

Upvotes: 4

Views: 2856

Answers (2)

Adam S
Adam S

Reputation: 501

Taxilian's answer is perfect except I'm not using Lodash so I implemented _.omit. Here is my result.

function annotatedStateObject(state, $current) {
    state = angular.extend({}, state);
    var resolveData = $current.locals.resolve.$$values;
    state.params = resolveData.$stateParams;
    state.resolve = omit(resolveData, '$stateParams');
    state.includes = $current.includes;
    return state;
}

function omit(obj, arr) {
    arr = Array.isArray(arr) ? arr : [arr];
    arr.forEach(function(key){
        delete(obj[key]);
    });
    return obj;
}

Upvotes: 0

taxilian
taxilian

Reputation: 14324

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!

Upvotes: 13

Related Questions