2016-11-30 61 views
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(); 
}); 
+0

我不确定这一点,但是当状态为200,并且您正在设置证书时,您可能无法访问您的$ scope,因此它们最终未定义,尝试从后端返回用户名,并访问从response.username或response.token,或任何你需要在那里。 – rule

+0

感谢您的回复。在那里尝试,但没有成功。 response.username肯定有用户名好,但一旦页面发生变化,变量保持未定义状态。 – devemcn

+0

我刚才注意到的另一件事,试着改变这两行: service.setCredentials = function(username,password){ this.username = username; }; service.getCredentials = function(){ return this.username; }; – rule

回答

0

的问题是,你的authService没有你从你的控制器调用登录方法:

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,因为它正在映射您尝试分配给的变量。这导致用户名值未定义。