我正在尝试向我的golang/angular应用添加身份验证。后端身份验证可以正常工作,并记录用户已登录,但 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();
});

最佳答案

问题是您的authService没有您从 Controller 调用的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,因为它遮盖了您试图分配给该变量的位置。这导致用户名值未定义。

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

10-11 22:36
查看更多