我想有两个主页,第一个是未登录的用户,第二个是登录用户.
这是我目前的设置:
.config(function ($stateProvider,$urlRouterProvider,$locationProvider,$httpProvider) { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); $httpProvider.interceptors.push('authInterceptor'); }) .factory('authInterceptor',function ($rootScope,$q,$cookieStore,$location) { return { // Add authorization token to headers request: function (config) { config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; },// Intercept 401s and redirect you to login responseError: function(response) { if(response.status === 401) { $location.path('/login'); // remove any stale tokens $cookieStore.remove('token'); return $q.reject(response); } else { return $q.reject(response); } } }; }) .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 (next.authenticate && !Auth.isLoggedIn()) { $location.path('/login'); } }); }); .config(function ($stateProvider) { $stateProvider .state('main',{ url: '/',templateUrl: 'app/main/main.html',controller: 'MainCtrl',title: 'Home',mainClass: 'home',headerSearch: true }); });
我怎么能重新配置这个,所以我可以做如下的事情:
.config(function ($stateProvider) { $stateProvider .state('welcome',{ url: '/',templateUrl: 'app/welcome/welcome.html',controller: 'WelcomeCtrl',title: 'Welcome',mainClass: 'welcome',isLoggedIn: false }); $stateProvider .state('main',isLoggedIn: true }); });
只是想表明,我们如何管理身份验证驱动的状态访问.基于这个
answer及其
plunker,我们可以通过数据设置丰富每个州(只有经过身份验证的用户才能访问),在此解释:
Attach Custom Data to State Objects(引用:)
You can attach custom data to the state object (we recommend using a data property to avoid conflicts)…
所以让我们有一些公共访问状态:
// SEE no explicit data defined .state('public',{ url : '/public',template : '<div>public</div>',}) // the log-on screen .state('login',{ url : '/login',templateUrl : 'tpl.login.html',controller : 'UserCtrl',}) ...
还有一些私人访问:
// DATA is used - saying I need authentication .state('some',{ url : '/some',template : '<div>some</div>',data : {requiresLogin : true },// HERE }) .state('other',{ url : '/other',template : '<div>other</div>',// HERE })
这可能会挂在状态变化上:
.run(['$rootScope','$state','User',function($rootScope,$state,User) { $rootScope.$on('$stateChangeStart',function(event,toState,toParams,fromState,fromParams) { var isAuthenticationrequired = toState.data && toState.data.requiresLogin && !User.isLoggedIn ; if(isAuthenticationrequired) { event.preventDefault(); $state.go('login'); } }); }])
有类似的Q&我试图展示重定向Authenticated和Not Authenticated用户的概念:
> Angular UI Router: nested states for home to differentiate logged in and logged out
也许这可以帮助我们了解一下,我们如何使用ui-router,以及它的事件’$stateChangeStart’来挂钩我们的决策经理 – 以及它强制重定向……