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

时间:2015-05-14 22:38:22

标签: angularjs authorization angular-ui-router

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

我想将authorized分配给网址的: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)

1 个答案:

答案 0 :(得分:1)

这可以使用$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