2016-09-13 32 views
5

我正在升級到[email protected]並試圖找出如果用戶沒有必要的權限,將用戶重定向到其他狀態的最佳方式是什麼。基於用戶角色的UI-Router 1.0重定向

這是我有:

.state('company_dashboard', { 
    url: '/dashboard', 
    templateUrl: 'dashboard.html', 
    controller: 'CompanyDashboardCtrl', 
    resolve: { 
     user: function(UserService) { 
      return UserService.getActiveUser(); 
     }, 
     company: function(UserService) { 
      return CompanyService.getActiveCompany(); 
     }, 
     permissions: function(CompanyService, user, company){ 
      return CompanyService.getUserPermissions(company, user); 
     } 
    }, 
    onEnter: function($state, permissions) { 
     if (permissions.canAccessDashboard === false) 
      return $state.go('company_landing_page'); 
    } 
}) 

上面的例子作品,但它記錄了以下錯誤:TransitionRejection(type: 2, message: The transition has been superseded by a different transition, detail: Transition#1(''{} -> 'company_landing_page'{}))這讓我覺得,應該有更好的方式。

旁邊的問題,在resolve期間檢查權限是否是一個好習慣?

UPDATE:

更改$state.go()$state.target()幫我擺脫控制檯錯誤的。 This comment已幫助。 雖然這個問題的立場,我是否在做這個地方呢?

+0

我用來檢查由spring或後端框架構建的模板的權限,我認爲檢查前端的權限並不好,因爲每個人都可以看到代碼。 –

回答

1

我將數據屬性添加到您的狀態如下:

.state('company_dashboard', { 
    data: { 
      requiresAuthentication: true 
    } 
} 

然後:

app.run(function ($rootScope, $state) { 
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) { 
     // Check if user is authenticated 
     // And route requires authentication 
     if (!toState.data.requiresAuthentication) { 
      $state.go(toState.name, toParams); 
     } else if (user && toState.data.requiresAuthentication) { 
      $state.go(toState.name, toParams); 
     } else { 
      $state.go('login'); 
     } 
    }); 
}); 

這似乎是工作得很好,即使我相信它可以更精緻,但我希望這給你一個關於你如何進行的想法。