1
我正在尝试向我的golang/angular应用添加身份验证。后端身份验证正常工作并记录用户已登录但角度部分未按预期工作,它不会将用户名设置为成功登录和更改页面时未设置用户名。AngularJS身份验证不能按预期工作
app.js
blog.controller('LoginCtrl', function($scope, $http, $window, authService){
$scope.login = function({
authService.Login($scope.username, $scope.password, function(response, status){
if(status == 200){
authService.setCredentials($scope.username, $scope.password);
$window.location.href="/";
} else {
$scope.invalidLogin = true;
}
});
};
});
blog.factory('authService', function(username, password, callback){
var service = {};
var username = "";
$http.post('/login', {Username : username, Password: password}).
success(function(response, status){
service.setCredentials(username, password);
callback(response, status);
});
service.setCredentials = function(username, password){
username = username;
};
service.getCredentials = function(){
return username;
};
return service;
});
blog.controller('NavCtrl', function($scope, $rootScope, authService){
$scope.isAuth = (authService.getCredentials() != "");
console.log("username: " + authService.getCredentials());
$scope.username = authService.getCredentials();
});
我不确定这一点,但是当状态为200,并且您正在设置证书时,您可能无法访问您的$ scope,因此它们最终未定义,尝试从后端返回用户名,并访问从response.username或response.token,或任何你需要在那里。 – rule
感谢您的回复。在那里尝试,但没有成功。 response.username肯定有用户名好,但一旦页面发生变化,变量保持未定义状态。 – devemcn
我刚才注意到的另一件事,试着改变这两行: service.setCredentials = function(username,password){ this.username = username; }; service.getCredentials = function(){ return this.username; }; – rule