您可以创建一个authInterceptor工厂并将其推入interceptors.
此方法将始终检查用户是否在每个页面上登录,如果用户未通过身份验证,则会将用户扔到登录页面
出于全局错误处理、身份验证或任何类型的请求的同步或异步预处理或响应的后处理的目的,希望能够在请求被移交给服务器之前拦截请求并在响应被移交给之前拦截它们启动这些请求的应用程序代码。拦截器利用Promise API 来满足同步和异步预处理的需求。
了解有关拦截器的更多信息
'use strict';
angular.module('app', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
.otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push('authInterceptor');
})
.factory('authInterceptor', function($rootScope, $q, $cookieStore, $location) {
return {
// Add authorization token to headers
request: function(config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if (response.status === 401) {
$location.path('/login');
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
} else {
return $q.reject(response);
}
}
};
})
.run(function($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function(event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
$location.path('/login');
}
});
});
})
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if ($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function() {
return currentUser.hasOwnProperty('role');
},
/**
* Waits for currentUser to resolve before checking if user is logged in
*/
isLoggedInAsync: function(cb) {
if (currentUser.hasOwnProperty('$promise')) {
currentUser.$promise.then(function() {
cb(true);
}).catch(function() {
cb(false);
});
} else if (currentUser.hasOwnProperty('role')) {
cb(true);
} else {
cb(false);
}
}
};
})
.factory('User', function($resource) {
return $resource('/api/users/:id/:controller', {
id: '@_id'
}
});
});
使用上述机制,您可以使用Auth服务以任何方式获取user信息,controller或者directives:
.controller('MainCtrl', function ($scope, Auth) {
$scope.currentUser = Auth.getCurrentUser;
});
在模板文件中:
<div ng-controller="MainCtrl">
<p> Hi {{currentUser().name}}!</p>
</div>
注意:您需要创建适当的 REST API 才能获取正确的user数据