Angularjs ui-router; How to get preload permission value when trigger $ stateChangeSuccess?

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

as above, state configuration, how can I get the value of "person" in the call function of $ stateChangeSuccess?

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams) {
    // I want get the 'person' value in this function, what should I do?
});
+4
source share
2 answers

We had the same problem. We solved this based on some internal details of the ui-router implementation; this means that it may 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;
}

This will get the parameters, and includes all (permitted) permission objects. We use this in the callback like this:

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

    var person = toState.resolve.person;
}

I hope this helps!

+11
source

, , Lodash, _.omit. .

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

Source: https://habr.com/ru/post/1547601/


All Articles