好的,所以我有一个url“/ securepage”的状态,我需要检查每当用户尝试访问它。所以我看到有一个onEnter函数我可以使用。但我似乎无法忍受这个范围和服务。我究竟做错了什么?
.state('securepage',{ url: "/securepage",template: securepage.html,onEnter: function(){ // if (!$scope.main.isAuthenticated) $state.go("/login"); // if (!myLoginService.currentUser()) $state.go("/login");
我看到的当前选项是使用解决方案和/或检查控制器中的身份验证。但是不要一个口令检查更好地放在onEnter?
今天遇到类似的问题。花了一整天,终于找到了一个可行的解决方案,而不是这里已经提出的解决方案。
我的主要目标是找到简单有效的方式来选择性地保护特定的网页。在HTML或任何相关控制器加载或调用之前,需要执行安全检查。如果检查失败,则页面可能转发到其他地方,而其他控制器没有任何副作用。
我尝试了其他建议的方法。每个人都有自己的一套问题:
>使用OnEnter:
>在进行异步调用进行安全检查时,无法阻止ui-router继续状态转换。
>使用$ rootScope。$ on(‘$ stateChangeStart’):
>查询安全检查状态的管理将与$ stateProvider.state()定义分离。理想情况下,我宁愿在一个地方查看所有关于一个状态定义的定义。虽然这不是一个showstopper,但并不理想。
>一个更大的问题是$ stateChangeStart事件没有被调用来初始加载一个页面。这是一个showstopper。
我的解决方案是使用一个resolve函数来定义一个承诺,这些承诺会导致视图控制器在调用之前等待延迟完成。这完全可以阻止控制器以异步方式启动。
以下是我使用的代码的粗略概述:
.config(['$stateProvider',function ($stateProvider) { // Handler for Restricting Access to a page using the state.resolve call var accessRestrictionHandler = function($q,$rootScope,$state) { var deferred = $q.defer(); // make sure user is logged in asyncCheckForLogin(function(status) { if (status != "Logged In") { // You may save target page URL in cookie for use after login successful later // To get the relative target URL,it is equal to ("#" + this.url). // The "this" here is the current scope for the parent state structure of the resolve call. $state.go("loginPage"); } else // if logged in,continue to load the controllers. Controllers should not start till resolve() is called. deferred.resolve(); }.bind(this)); return deferred.promise; }; $stateProvider .state('userProfile',{ url: '/userProfile',views: { 'main': { templateUrl: 'userProfile.html',controller: 'userProfileCtrl' } },// SIMPLY add the line below to all states that you want to secure resolve: { loginrequired : accessRestrictionHandler } }) .state(.... some other state) .state(.... some other state); }]);
我希望这将帮助你们中的一些人。