gpt4 book ai didi

javascript - AngularJS 身份验证未按预期工作

转载 作者:IT王子 更新时间:2023-10-29 02:22:37 26 4
gpt4 key购买 nike

我正在尝试向我的 golang/angular 应用程序添加身份验证。后端身份验证工作正常并记录用户已登录但 Angular 部分未按预期工作,它没有设置用户名,因为当它成功登录和更改页面时,用户名未设置。

应用程序.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();
});

最佳答案

问题是您的 authService 没有您从 Controller 调用的登录方法:

blog.controller('LoginCtrl', function($scope, $http, $window, authService){ 
$scope.login = function({
// Well there's your problem!
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;
}
});
};
});

相反,您需要像这样在您的工厂中定义您的登录方法:

myApp.factory('authService', function(){
var service = {};
var username = "";

service.setCredentials = function(loginUsername, password){
username = loginUsername;
};

service.getCredentials = function(){
return username;
};

service.Login = function(loginUsername, password, callback){
$http.post('/login', {Username : loginUsername, Password: password}).
success(function(response, status){
service.setCredentials(loginUsername, password);
callback(response, status);
});
}

return service;
});

请注意,我还将用户名函数参数更改为 loginUsername,因为它隐藏了您尝试分配给的变量。这导致用户名值未定义。

关于javascript - AngularJS 身份验证未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886911/

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