javascript - AngularJS 无法显示身份验证状态

标签 javascript html angularjs authentication

我对 AngularJS 很陌生,所以首先道歉!

我有一个 Angular 应用程序,在后端使用 REST API 来登录/注销用户

但是我试图在 Angular 前端显示用户的登录状态,但没有取得太大成功。

我的用户使用“authService.js”登录和注销:

app.factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {

    // dec the home of the API
    var serviceBase = '<domain>' // remember to change this to the current domain that the API is being hosted!
    var authServiceFactory = {};

    // Local Authentication Data
    var _authentication = {
        isAuth: false,
        userName: ""
    };

    // Attempt to log in the user here
    var _login = function (loginData) {
        // This will be the body data of the login requesst
        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
        var deferred = $q.defer(); // This gets the async data (AngularJS Call)

        // Send a post request to the /token endpoint to request a login
        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(
            function (response) {
                // If the response was a 200 Success, then the user can be logged in locally
                // Store the auth token
                localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });
                // set local client data
                _authentication.isAuth = true;
                _authentication.userName = loginData.userName;
                // Return the promise
                deferred.resolve(response);
            }).error(function (err, status) {
                // Response from the HTTP was bad, i.e. not 200
                // flush the user and reject thee promise
                _logOut();
                deferred.reject(err);
            });
        return deferred.promise; // return the promise
    };

    // Remove the token from local storage
    var _logOut = function () {
        localStorageService.remove('authorizationData');
        _authentication.isAuth = false;
        _authentication.userName = "";
    };

    // This is run at start. Tries to get the autherizationData and if it is there then
    // the user is considered logged in
    var _fillAuthData = function () {
        var authData = localStorageService.get('authorizationData');
        if (authData) {
            _authentication.isAuth = true;
            _authentication.userName = authData.userName;
        }
    }

    // Assign all the attributs of the service facotry
    authServiceFactory.saveRegistration = _saveRegistration;
    authServiceFactory.login = _login;
    authServiceFactory.logOut = _logOut;
    authServiceFactory.fillAuthData = _fillAuthData;
    authServiceFactory.authentication = _authentication;

    console.log("Auth at end of factory:");
    console.log(_authentication.isAuth);

    // Return this object
    return authServiceFactory;
}]);

因此,这个工厂应该生成一个对象authServiceFactoryauthServiceFactory.authentication 对象是我需要向用户呈现的数据,特别是 .isAuth。从这里我可以隐藏链接、向用户显示用户名等...

在我的主 App.js 文件中,我有:

var app = angular.module('AngularAuthApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar']);

app.config(function ($routeProvider) {

    // Declaire routes...
    $routeProvider.when("/home", {
        controller: "homeController",
        templateUrl: "/app/views/home.html"
    });

    $routeProvider.when("/login", {
        controller: "loginController",
        templateUrl: "/app/views/login.html"
    });

    $routeProvider.when("/signup", {
        controller: "signupController",
        templateUrl: "/app/views/signup.html"
    });

    // redirect the user if they try to access anything else
    $routeProvider.otherwise({ redirectTo: "/home" });
});

// On the app running run the authService to get auth data
app.run(['authService', function (authService) {
    authService.fillAuthData();
}]);

// Set the application config
// Any http request push it though the authInterceptorService
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptorService');
}); 

注意app.run将从工厂收集当前的身份验证数据。

在我的主要单页 HTML 文档中,我有:

<!DOCTYPE html>
<html data-ng-app="AngularAuthApp">
<head>
    <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" />
    <link href="content/css/bootstrap.min.css" rel="stylesheet" />
    <link href="content/css/loading-bar.min.css" rel="stylesheet" />
    <link href="content/css/site.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
    <script src="scripts/bootstrap.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
    <div id="wrapper">
        <div id="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li ng-hide="!authentication.isAuth"><a href="#/chargers">Welcome {{authentication.userName}}</a></li>
                <li ng-hide="!authentication.isAuth"><a href="" data-ng-click="logOut()">Logout</a></li>
                <li ng-hide="authentication.isAuth"><a href="#/login"><span class="glyphicon glyphicon-user"></span> Login</a></li>
                <li ng-hide="authentication.isAuth"><a href="#/signup"><span class="glyphicon glyphicon-log-in"></span> Sign Up</a></li>
            </ul>
        </div>
    </div> ...

我的用户可以毫无问题地登录!我使用 chrome 调试器发现状态正在改变。但是我无法通过 HTML 反射(reflect)结果。用户登录时不会显示列表项。将 {{authentication.isAuth}} 添加到我的 html 页面不会显示任何内容。

如何隐藏/显示链接,并直观地表示用户当前已登录?

最佳答案

在 AuthFactory 中有一个 $rootScope 变量标志,并在成功登录后更新它。

$rootScope.isAuthenticated = false; // Not authenticated
function login(){
    $http.post('RESTcalls').then(function(data){
        $rootScope.isAuthenticated = true; // Authenticated
    })
}

关于javascript - AngularJS 无法显示身份验证状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37189843/

相关文章:

javascript - Ajax 按钮向下滑动并附加带有淡入效果的数据

javascript - 所见即所得多输入(jQuery 插件)

html - Bootstrap 4 添加悬停框阴影问题

javascript - jasmine spyOn on javascript 新日期

html - "Save as"来自 HTML 表单的响应

javascript - 一个 react 应用程序导入到另一个 react 应用程序中?

javascript - 使用 Javascript 验证 "Confirm password"输入是否会增加任何安全风险?

javascript - 将两个元素居中(高度基于容器和第二个元素的 IMG)

angularjs - 在 ionic 侧菜单标题中显示当前页面的标题

javascript - React superagent 的单个文件?