使用$ rootScope。$ on('$ routeChangeStart',function(event,next,current),如果路由需要身份验证,我将重定向到登录页面。
登录后,如何重定向回预期的路由?
最佳答案
这是对我有用的简化版本:
app = angular.module('ngApp', []).config(function ($routeProvider) {
$routeProvider
.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'dashboardController',
loginRequired: true //
})
.when('/login', {
templateUrl: 'login.html',
controller: 'loginController'
})
.otherwise({redirectTo: '/login'})
});
然后在应用程序的运行块中:
app.run(function ($location, $rootScope) {
var postLogInRoute;
$rootScope.$on('$routeChangeStart', function (event, nextRoute, currentRoute) {
//if login required and you're logged out, capture the current path
if (nextRoute.loginRequired && Account.loggedOut()) {
postLogInRoute = $location.path();
$location.path('/login').replace();
} else if (postLogInRoute && Account.loggedIn()) {
//once logged in, redirect to the last route and reset it
$location.path(postLogInRoute).replace();
postLogInRoute = null;
}
});
});