如何访问 $stateProvider.state 的 stateConfig 对象中的 url 参数?

How do you access url parameters inside of $stateProvider.state's stateConfig object?

.state('edit', {
  url: '/edit/:id',
  templateUrl: 'app/skims/form/form.html',
  controller: 'FormCtrl as formCtrl',
  authenticate: {
    loggedIn: true,
    authorized: // :id
  }
})

我想将 authorized 分配给 URL 的 :id 部分。有办法吗?


我想这样做的原因是我可以设置授权。

.run(function ($rootScope, $location, Auth) {
  // Redirect to login if route requires auth and you're not logged in
  $rootScope.$on('$stateChangeStart', function (event, next) {
    if (typeof next.authenticate !== 'undefined') {
      Auth.isLoggedInAsync(function(loggedIn) {
        if (next.authenticate.loggedIn && !loggedIn) {
          alert('Must be logged in to access this route.');
          $location.path('/login');
        }
        if ( next.authenticate.authorized 
          && Auth.getCurrentUser()._id !== next.authenticate.authorized) {
          alert('Unauthorized. Must be signed in as the right user.');
          $location.path('/login');
        }
        if (next.authenticate.admin && !Auth.isAdmin()) {
          alert('Must be an admin to access this route.');
          $location.path('/login');
        }
      });
    }
  });

特别是

...
if ( next.authenticate.authorized 
  && Auth.getCurrentUser()._id !== next.authenticate.authorized)

这可以通过 $stateChangeStart 事件的更多婴儿车来解决

// instead of this
$rootScope.$on('$stateChangeStart', function (event, next) {

// we can use this
$rootScope.$on('$stateChangeStart'
       , function (event, toState, toParams, fromState, fromParams) {

这意味着,我们现在可以访问 toParams 中所有传递的参数。我们可以这样评价:

// instead of this
// ...
// && Auth.getCurrentUser()._id !== next.authenticate.authorized.

// we can use 
Auth.getCurrentUser()._id !== toParams.id