使用$ rootScope.$ on('$ routeChangeStart',function(event,next,current)),如果路由需要身份验证,我将重定向到登录页面.这非常有效.
登录后如何重定向回预期的路线?
小智 24
这是对我有用的简化版本:
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'})
});
Run Code Online (Sandbox Code Playgroud)
然后在应用程序的运行块中:
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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
这是我如何做的一个例子,希望它有所帮助:
在路由提供者上,首先以某种方式设置公共访问:
// Just a demo on how the routes were set up to determine public access
angular.module('ngApp', []).config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller : 'MainController',
})
.when('/login', {
templateUrl : 'views/login.html',
controller : 'LoginController',
publicAccess : true // This is used in $routeChangeStart later
});
});
});
Run Code Online (Sandbox Code Playgroud)
然后:
$rootScope.$on('$routeChangeStart', function(event, next, current) {
var publicAccess = next.publicAccess || false;
// This is just a service I made, this is how I check logged in status
// AuthenticationService.check() returns a promise
AuthenticationService.check().then(function() {
// As this is a promise, this block signals that the user is logged in
// If the page is marked as public access, then redirect to private area
if (publicAccess)
$location.path('/').replace();
}, function() {
// Since this segment of the promise signals that the user is not
// logged in, if the page is not publicly accessible, redirect to login
if (!publicAccess)
$location.path('/login').replace();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27370 次 |
| 最近记录: |