AngularJS身份验证无法按预期工作

时间:2016-11-30 11:14:02

标签: javascript angularjs go

我正在尝试为golang / angular应用添加身份验证。后端身份验证工作正常并记录用户已登录但角度部分未按预期工作,它不会将用户名设置为成功登录和更改页面时,用户名未设置。

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();
});

1 个答案:

答案 0 :(得分:0)

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

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;
              }
          });
      };
});

相反,您需要在工厂中定义您的Login方法,如下所示:

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,因为它会影响您尝试分配的变量。这导致用户名值未定义。