1
私はgolang/angleアプリケーションに認証を追加しようとしています。バックエンド認証がうまく動作し、ユーザーがログインしているが角度部分が期待どおりに機能していない、ログインに成功してページが変更されたときにユーザー名が設定されていないとユーザー名が設定されません。AngularJS認証が正常に動作しない
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;
}
});
};
});
代わりに、あなたが定義する必要があります。問題は、あなたのAuthServiceがあなたのコントローラから呼び出しているログインの方法を持っていないということです
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は間違いなくユーザー名をOKにしていますが、ページの変更が発生すると変数は未定義のままです。 – devemcn
私は今気付いたちょっと別のことは、この2行を変更しようとしてください: service.setCredentials = function(username、password){ this.username = username; }; service.getCredentials = function(){ return this.username; }; – rule