angularjs – 如何从$stateChangeStart访问UI-Router根状态的“r
我正在尝试在我的应用程序中实施用户身份验证和访问检查系统,但是我不断打击路障。我觉得这次我有正确的方法,但是我有一个最后一个障碍。
一点点背景:我试图把所有的代码放到$ rootScope.on($ startChangeStart),它的工作,可怕的…但它的工作。路由始终被重定向,但是由于后端的auth检查,它显示第一个请求页面1/2秒,然后每次重定向页面。因此,我尝试通过在$ startChangeStart函数的开始处调用evt.preventDefault()来尝试“暂停”页面加载,但是尝试将用户返回到原始路由,导致路由器中的无限循环。 所以经过更多的研究和阅读很多堆栈文章,我确定’解决:’是放置验证检查以确保页面没有加载发生时的适当的地方,然后重定向用户,如果需要从$ startChangeStart。 ($状态和事件总是未定义,我试图将它们注入到一个解析函数中)看起来像获胜组合。 我的问题:我在我的应用程序中的根状态的决心:’主’ 这是为了避免代码冗余,但是我无法确定如何从$ stateChangeStart函数访问根状态的属性,因此解决结果。 toState是子状态,而fromState是以前的状态,或者是’^’路由的抽象状态 我必须把决心放在每一个孩子的状态上才能工作,还是从这个角度来访问根状态? 基本应用设置: angular.module('App',['ui.router','ui.bootstrap','ui.event','AngularGM','ngResource']) .config(['$urlRouterProvider','$stateProvider',function($urlRouterProvider,$stateProvider){ $urlRouterProvider .when('/home','/') .when('','/') .when('/sign-up/joe','/sign-up') .otherwise('/'); $stateProvider .state('main',{ url: '',abstract: true,templateUrl: 'views/main.html',controller: 'MainCtrl',resolve: { checkAccess: ['accountService',function(accountService) { accountService.checkAuth(function(){ accountService.checkAccess(function (access){ return access; }); }); }] } }) .state('main.home',templateUrl: 'views/home.html',controller: 'HomeCtrl' }) .state('main.home.index',{ url: '/',templateUrl: 'views/home/index.html' }); .run(['$rootScope','$state','$stateParams','accountService',function ($rootScope,$state,$stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; $rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams) { console.dir(toState); console.dir(toParams); console.dir(fromState); console.dir(fromParams); if (!toState.checkAccess.allowed) { event.preventDefault(); $state.transitionTo(toState.checkAccess.newState); } }); }]); 这是console.dir()对两个状态对象的调用的输出: Object name: "main.home.index" templateUrl: "views/home/index.html" url: "/" __proto__: Object Object controller: "PlacesCtrl" name: "main.places.search" templateUrl: "views/places.html" url: "/places" __proto__: Object 更新 哎呀,忘了提到AngularJS版本是v1.2.0-rc.2 $ state.current console.dir() Object abstract: true name: "" url: "^" views: null __proto__: Object
是的,我相信你可以从$ stateChangeStart函数访问根状态。
当使用纯AngularJS时,我通常使用当前的$$路由 例如,使用以下路由 .when('/home',{ title:'Home',bodyClass: 'meetings',controler: 'HomeCtrl' }) 我可以这样访问根状态 $rootScope.$on('$routeChangeSuccess',function (event,current,previous) { if (current.$$route) { $rootScope.title = current.$$route.title; $rootScope.bodyClass = current.$$route.bodyClass; } }); 使用ui-router它只是有点不同,因为它被称为$ state.current。并且您可以访问与您所击打的任何路线相关联的所有属性(例如:$ state.current.url) 所以你的代码你可以有这样的东西 .run(['$rootScope',$stateParams) { $rootScope.$on('$stateChangeStart',fromParams) { console.log($state.current.url); }); }]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |