gpt4 book ai didi

php - 当用户未登录或用户尝试使用 angularjs 直接从 URL 访问页面时重定向到登录

转载 作者:可可西里 更新时间:2023-10-31 23:02:56 24 4
gpt4 key购买 nike

我正在创建一个小项目,如果用户 Angular 色是销售,那么在登录后它将用户重定向到销售表单页面。现在,如果用户尝试通过在 URL 中输入其路径来访问 Sales form 页面并且用户未登录,我如何将用户重定向到登录页面。这是我的 Angular 部分。

app.controller('LoginCtrl',function($scope,$http,$window){

$scope.login = function(){
data={
email:$scope.email,
pwd:$scope.pwd
}
$http.post("widget/login.php",data).success(function(data){
console.log(data);
if(!data.success){
$scope.errorMsg="username or password is incorrect";
}
else{
$scope.role=data.role;
$scope.id=data.id;
if(data.role == "admin"){
$window.location.href="AdminPage.html";
}
else if(data.role == "Sales"){
$window.location.href="sales_form.html";
}
else if(data.role == "Account"){
$window.location.href="account_form.html";
}
else if(data.role == "Technical"){
$window.location.href="Technical_Form.html";
}
else{
$scope.errorMsg="username or password is incorrect";
}
}

});
}

});

如果用户未登录或尝试直接从 URL 访问页面,我如何将用户重定向到登录页面。还有一件事我使用 PHP 作为后端,您可以在 $http.post 部分看到它,因此请相应地给出您的答案。感谢帮助并提前感谢您。

最佳答案

你应该使用 Angular 路由而不是 $window.location.href。

让我向您展示如何使用 ui-router。在加载 Angular 库后在 index.html 中添加这一行。

<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>

在你的 app.js 中

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider

// HOME STATES AND NESTED VIEWS ========================================
.state('login', {
url: '/login',
templateUrl: 'login.html',
controller : 'LoginController'

})

// SALES PAGE AND MULTIPLE NAMED VIEWS =================================
.state('sales', {
url: '/sales',
templateUrl: 'sales_form.html',
controller : 'SalesController'
......
......

});
});

现在在你的 Controller 中

   app.controller('LoginCtrl',function($scope,$http,$window,$state){

$scope.login = function(){
data={
email:$scope.email,
pwd:$scope.pwd
}
$http.post("widget/login.php",data).success(function(data){
console.log(data);
if(!data.success){
$scope.errorMsg="username or password is incorrect";
$state.go('login');

}
else{
$scope.role=data.role;
$scope.id=data.id;
if(data.role == "admin"){
$state.go('admin'); //add admin state as admin in ui-router like sales
}
else if(data.role == "Sales"){
$state.go('sales');
}
.....

else{
$scope.errorMsg="username or password is incorrect";
$state.go('login');
}
}

});
}
});

关于php - 当用户未登录或用户尝试使用 angularjs 直接从 URL 访问页面时重定向到登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43860893/

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