1
我對AngularJS非常陌生,所以先道歉!AngularJS無法顯示身份驗證狀態
我有一個角應用程序使用REST API在後臺記錄用戶的輸入/輸出
但是我想顯示用戶的登錄上的角前端的狀態,但沒有取得多大成功。
我的用戶登錄和退出使用 「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;
}]);
所以,這個工廠應該產生一個對象authServiceFactory
。 authServiceFactory.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反映結果。列表項不會在用戶登錄時顯示。將{{authentication.isAuth}}添加到我的html頁面不會顯示任何內容。
如何隱藏/顯示鏈接,並可視化地表示用戶當前已登錄?
我得到$ rootScope是不確定的,所以如果它是不確定的,你有你的腳本來定義它這個方法是行不通的不幸 – Harvey
。 – Vinay
在使用它之前,在您的控制器/工廠中注入$ rootScope。 – Vinay