AngularJS在run函数中访问$ stateParams

nik*_*ong 2 javascript angularjs angular-ui-router

我希望能够访问我的run函数中的url参数,并根据这些参数进行操作.但是,我很惊讶地看到ui.router的$stateParams对象在我的run函数中是空的.

angular.module('app', ['ui.router'])
.run(['$rootScope', '$state', '$stateParams', '$location', function($rootScope, $state, $stateParams, $location) {
    $rootScope.$state = $state;
    $rootScope.location = $location;
    $rootScope.$stateParams = $stateParams;
    $rootScope.$on('$stateChangeStart', function(event, toState) {
      if (toState.name === 'main') {
      event.preventDefault();
      $state.go('main.child', {

        param: 1

      })
      }
    });
    console.log('$stateParams is empty!');
    console.log($stateParams);
    console.log($rootScope.$stateParams);
}])
.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {

    $stateProvider
        .state('main', {

            url: '',
            template: '<div>hey</div><div ui-view></div>'

        })
        .state('main.child', {

            url: '/:param',
            template: 'child state template'


        });
}]);
Run Code Online (Sandbox Code Playgroud)

是否可以访问从$stateParamsrun函数中访问的params ?或者它们仅在config功能中可用?为什么run函数中无法访问它们?

Plnkr:http://plnkr.co/edit/1YXKRmR48LyxbGXWq66Y?p=preview

谢谢你的帮助.

Jan*_*isP 8

看起来您正在使用StateChangeStart事件,您可以在此事件中访问参数:

 $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//you code goes here
console.log(toParams);
}
Run Code Online (Sandbox Code Playgroud)

我用它来为参数添加一些自定义逻辑(身份验证重定向)