gpt4 book ai didi

javascript - 如果已经使用 angularjs 登录,如何避免显示登录页面?

转载 作者:行者123 更新时间:2023-11-30 12:42:36 24 4
gpt4 key购买 nike

我正在使用 AngularJS 构建一个应用程序。我有身份验证工作,当用户未获得授权时,他将被重定向到显示登录表单的 #/login

但是,当用户通过身份验证并手动转到 #/login 时,登录页面再次显示,尽管用户仍处于登录状态。有什么办法可以将他定向到在那种情况下是主页?

这就是我进行重定向的方式:

$routeProvider
.when( '/ds', {
templateUrl: 'partials/datasheets-list.html',
controller: 'DatasheetsListCtrl'
} )
.when( '/ds/:datasheetId', {
templateUrl: 'partials/datasheet-detail.html',
controller: 'DatasheetDetailCtrl'
} )
.when( '/login', {
templateUrl: 'partials/login.html',
controller: 'LoginController'
} )
.otherwise( {
redirectTo: '/ds'
} );

这是 LoginController 的代码:

var datasheetsControllers = angular.module( 'datasheetsControllers', ['ngCookies', 'datasheetsServices'] );

datasheetsControllers.controller( 'LoginController', ['$scope', '$rootScope', '$location', '$http', '$cookieStore', 'LoginService', function ( $scope, $rootScope, $location, $http, $cookieStore, LoginService )
{

$scope.login = function ()
{
LoginService.authenticate( $.param( {username: $scope.username, password: $scope.password} ), function ( user )
{
$rootScope.user = user;
// Authenticate AngularJS Ajax calls
$http.defaults.headers.common[ xAuthTokenHeaderName ] = user.token;

// Authenticate jQuery Ajax calls
var headers = {};
headers[xAuthTokenHeaderName] = user.token;
$.ajaxSetup({
headers: headers
});
$cookieStore.put( 'user', user );
$location.path( "/" );
} );
};
}] );

最佳答案

我认为通常的做法是监听 $routeChangeStart 事件。

$scope.$on('$routeChangeStart', function(scope, next, current){
//...
});

在这里你可以询问下一个路径是否是登录,然后你可以检查用户是否已经登录的身份验证服务。如果他是,像往常一样使用重定向将他直接重定向到登录

或者,您可以在路由对象中使用 resolve 回调

when('/login', { controller: 'LoginCtrl', templateUrl: '', resolve : {
load : function ( ... ) { ... }
})

SO上已经有类似的东西了

AngularJS - Need some combination of $routeChangeStart and $locationChangeStart

Fire a callback when route is changed (animations, loaders etc) in AngularJS

关于javascript - 如果已经使用 angularjs 登录,如何避免显示登录页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876817/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com