gpt4 book ai didi

javascript - 如何在 Angular JS 中验证状态

转载 作者:行者123 更新时间:2023-12-03 06:21:58 25 4
gpt4 key购买 nike

我想验证我的 Angular 应用程序中的状态。可用的资源太复杂,我不明白为什么。

我的简单逻辑是设置一个变量

$rootScope.is_authenticated = true

并在加载状态时检查变量是否为真。

我怎样才能实现这一点以及为什么登录和身份验证在 Angular 中如此复杂。

我的配置文件

.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'partials/auth.html',
controller: 'AuthCtrl'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'partials/dashboard.html',
controller: 'DashboardCtrl',
resolve:{
check: function($rootScope, $state){
if($rootScope.is_authenticated == true){
return true;
}
else{
$state.go('auth');
}
}
}
})

$urlRouterProvider
.otherwise("/auth");

我的 AuthCtrl 中的登录功能

//login
$scope.login = function(user){
console.log(user);
$http({
method : "POST",
url : "myapi.com/login",
data : user
}).then(function mySucces(response) {
$scope.data = response.data;
$rootScope.is_authenticated = true;
$state.go('dashbooard');
}, function myError(response) {
$scope.error = response.statusText;
$rootScope.is_authenticated = false;
});
}

注销功能

 $scope.logout = function(){
$rootScope.is_authenticated = false;
$state.go('auth');
}

我已经向我的状态添加了另一个属性,resolve。现在只有用户登录后才能访问状态。这是正确的方法吗?如果不正确,与之相关的问题是什么

最佳答案

我通过创建Angular的run和service方法实现了登录、认证

我的代码片段:

routes.js ://使用身份验证 key 更新代码

.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('auth', {
url: '/auth',
templateUrl: 'partials/auth.html',
controller: 'AuthCtrl'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: 'partials/dashboard.html',
controller: 'DashboardCtrl',
authenticate: true // add this to the routes you want the users' should be authenticated
})

$urlRouterProvider.otherwise("/auth");

运行.js:

(function () {
'use strict';

angular.module('app').run(runBlock);

runBlock.$inject = ['$rootScope', '$state', '$log', 'AuthService'];

function runBlock($rootScope, $state, $log, AuthService) {
// detects change of state started
var rootScopeOn = $rootScope.$on('$stateChangeStart', function (event, next, params) {
// next.authenticate - if states needs to be authenticated
if (next.authenticate && !$rootScope.currentUser) {
event.preventDefault();


if (AuthService.isLoggedIn()) {
AuthService.getLoggedInUser().then(function (response, status) {
$log.debug('Run - runBlock() - status : ', status);
if (!response) {
$state.go('login');
} else {
$state.go(next, params);
}
}, function () {
$log.error('Run - runBlock() : ERROR');
$state.go('login');
});
} else {
$state.go('login');
}
}
});
$log.debug('Run - runBlock() - rootScopeOn : ', rootScopeOn);
}
})();

auth.js:

(function() {
'use strict';

angular.module('app').factory('AuthService', AuthService);

function AuthService($http, $q, $log, $rootScope, User) {
function login(email, password) {
// TODO : change the code here to consume your http post, I use ng-resource so code is according to that
return User.login({ username: email, password: password }).$promise.then(function(response) {
$rootScope.currentUser = {
id: response.user.id,
email: response.user.email,
userame: response.user.username,
emailVerified: response.user.emailVerified
};
});
}

function logout() {
return User.logout().$promise.then(function() {
$rootScope.currentUser = null;
});
}

function isLoggedIn() {
return User.isAuthenticated();
}

function getUserInfo() {
return $rootScope.currentUser;
}

function setUserInfo(data) {
$rootScope.currentUser = {
id: data.id,
role: data.role,
email: data.email,
userame: data.username,
emailVerified: data.emailVerified
};
}

function getLoggedInUser() {
var deferred = $q.defer();
User.getCurrent().$promise.then(function(response) {
if(angular.isDefined(response.error)) {
if(response.error.status === 401) {
deferred.resolve(false);
}
else {
setUserInfo(response);
deferred.resolve(getUserInfo());
}
}
else {
setUserInfo(response);
deferred.resolve(getUserInfo());
}
});
return deferred.promise;
}

function register(email, password) {
return User.create({
email: email,
password: password
}).$promise;
}

return {
login: login,
logout: logout,
register: register,
isLoggedIn : isLoggedIn,
getUserInfo: getUserInfo,
getLoggedInUser: getLoggedInUser
};
}
})();

关于javascript - 如何在 Angular JS 中验证状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38827006/

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