我正在使用angular-ui-route v0.3.1。
开展Angularjs SPA最近应用了rule()以允许不区分大小写的网址...
$urlRouterProvider.rule(function ($injector, $location) {
//what this function returns will be set as the $location.url
var path = $location.path(), normalized = path.toLowerCase();
if (path != normalized) {
//instead of returning a new url string, I'll just change the $location.path directly so I don't have to worry about constructing a new url string and so a new state change is not triggered
$location.replace().path(normalized);
}
// because we've returned nothing, no state change occurs
});
我也在监听$stateChangeStart
事件以检查用户是否未登录并将其重定向到登录页面
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (!('data' in toState) || !('access' in toState.data)) {
messageHandler.show({
message: 'Access undefined for this state',
messageType: messageHandler.messageTypes.error
});
event.preventDefault();
}
else
if (!auth.authorize(toState.data.access)) {
event.preventDefault();// this line cause my circular issue
if (!auth.isLoggedIn()) {
var redirectState = toState.name;
auth.login( redirectState);
}
else {
messageHandler.show({
message: 'Seems like you tried accessing a route you do not have access to : ' + toState.name,
messageType: messageHandler.messageTypes.warning
});
$state.go('unauthorized');
}
}
});
问题是角色过滤器会对网址进行规范化,在$stateChangeStart
事件中执行 event.preventDefault()时,规范化网址为被取消并再次发生循环。
任何帮助将不胜感激。