AngularJS – 显示/隐藏导航项目,如果用户login

我有一个单页的AngularJS应用程序,通过Mongoose与Express,node.js和MongoDB一起工作。 使用Passport进行用户pipe理/authentication。

我希望导航栏项目根据用户是否login进行更改。 我很难搞清楚如何实现它。

我发现用户是否通过http请求login:

server.js

 app.get('/checklogin',function(req,res){ if (req.user) res.send(true); else res.send(false); 

在前端,我有一个NavController使用Angular的$http服务调用它:

NavController.js

 angular.module('NavCtrl',[]).controller('NavController',function($scope,$http) { $scope.loggedIn = false; $scope.isLoggedIn = function() { $http.get('/checklogin') .success(function(data) { console.log(data); if (data === true) $scope.loggedIn = true; else $scope.loggedIn = false; }) .error(function(data) { console.log('error: ' + data); }); }; }; 

在我的导航中,我正在使用ng-showng-hide来确定哪些select应该可见。 当用户点击导航项时,我也触发了isLoggedIn()函数,检查用户是否每次点击都login。

的index.html

 <nav class="navbar navbar-inverse" role="navigation"> <div class="navbar-header"> <a class="navbar-brand" href="/">Home</a> </div> <ul class="nav navbar-nav"> <li ng-hide="loggedIn" ng-click="isLoggedIn()"> <a href="/login">Login</a> </li> <li ng-hide="loggedIn" ng-click="isLoggedIn()"> <a href="/signup">Sign up</a> </li> <li ng-show="loggedIn" ng-click="logOut(); isLoggedIn()"> <a href="#">Log out</a> </li> </ul> </nav> 

问题

在我的应用程序中还有其他地方,用户可以在NavController范围之外login/注销。 例如,login页面上有一个loginbutton,对应于LoginController。 我想有一个更好的方法来贯彻我的整个应用程序。

我怎样才能“观察” req.user是否为true ,并让我的导航项目做出相应的响应?

您可以使用$rootScope在整个应用程序中共享信息:

 .controller('NavController',function($scope,$http, $rootScope) { $scope.isLoggedIn = function() { $http.get('/checklogin') .success(function(data) { console.log(data); $rootScope.loggedIn = data; }) .error(function(data) { console.log('error: ' + data); }); }; }; 

现在您可以通过访问$rootScope.loggedIn来更改应用程序中其他位置的loggedIn值,方法与上面代码中的相同。

这就是说,你应该把相关的代码抽象成一个服务和一个指令。 这将允许您有一个中心位置来处理,login,注销和$rootScope.loggedIn状态。 如果你发布了其他相关代码,我可以用更具体的答案来帮助你

用户login成功后,您可以广播该事件。 如果用户login,则无需继续轮询您的服务器,您可以在内存中保留一个variables,告诉您是否有有效的会话。 您可以使用在服务器端设置的基于令牌的身份validation:

 services.factory('UserService', ['$resource', function($resource){ // represents guest user - not logged var user = { firstName : 'guest', lastName : 'user', preferredCurrency : "USD", shoppingCart : { totalItems : 0, total : 0 }, }; var resource = function() { return $resource('/myapp/rest/user/:id', { id: "@id"} )}; return { getResource: function() { return resource; }, getCurrentUser: function() { return user; }, setCurrentUser: function(userObj) { user = userObj; }, loadUser: function(id) { user = resource.get(id); } } }]); services.factory('AuthService', ['$resource', '$rootScope', '$http', '$location', 'AuthenticationService', function ($resource, $rootScope, $http, $location, AuthenticationService) { var authFactory = { authData: undefined }; authFactory.getAuthData = function () { return this.authData; }; authFactory.setAuthData = function (authData) { this.authData = { authId: authData.authId, authToken: authData.authToken, authPermission: authData.authPermission }; // broadcast the event to all interested listeners $rootScope.$broadcast('authChanged'); }; authFactory.isAuthenticated = function () { return !angular.isUndefined(this.getAuthData()); }; authFactory.login = function (user, functionObj) { return AuthenticationService.login(user, functionObj); }; return authFactory; }]); services.factory('AuthenticationService', ['$resource', function($resource){ return $resource('/myapp/rest/auth/', {}, { 'login': { method: "POST" } } ); }]); services.factory('authHttpRequestInterceptor', ['$injector', function ($injector) { var authHttpRequestInterceptor = { request: function ($request) { var authFactory = $injector.get('AuthService'); if (authFactory.isAuthenticated()) { $request.headers['auth-id'] = authFactory.getAuthData().authId; $request.headers['auth-token'] = authFactory.getAuthData().authToken; } return $request; } }; return authHttpRequestInterceptor; }]); 

控制器:

 controllers.controller('LoginCtrl', ['$scope', '$rootScope', 'AuthService', 'UserService', function LoginCtrl($scope, $rootScope, AuthService, UserService) { $scope.login = function () { AuthService.login($scope.userInfo, function (data) { AuthService.setAuthData(data); // set user info on user service to reflect on all UI components UserService.setCurrentUser(data.user); $location.path('/home/'); }); }; $scope.isLoggedIn = function () { return AuthService.isAuthenticated(); } $scope.user = UserService.getCurrentUser(); }]) 

您可以使用一些模板库(如EJS)在index.html中添加用户的会话数据。

只需添加ejs中间件:

 var ejs = require('ejs'); // Register ejs as .html. app.engine('.html', ejs.__express); 

如果您希望login在当前会话之外保持,您也可以使用$ localStorage。 我发现这个库对这些types的情况有很大的帮助。 ( https://github.com/grevory/angular-local-storage