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