2016-11-30 57 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,因爲它正在映射您嘗試分配給的變量。這導致用戶名值未定義。