【发布时间】:2015-09-30 16:51:45
【问题描述】:
我正在尝试在我的 Angular 应用程序中构建某种身份验证,并希望在用户未登录时重定向到外部 URL(基于 $http.get)。
当 event.preventDefault() 是 $stateChangeStart 的第一行时,我不知何故陷入了无限循环。
我在 stackoverflow 上看到了多个问题的答案,比如 “将 event.preventDefault() 放在 else 中的 state.go 之前”。但随后控制器被触发,并且在返回 promise 之前页面已经显示。
即使我将 event.preventDefault() 放在 else 中,也会发生一些奇怪的事情:
转到根 URL,它会在 URL 后自动添加 /#/,并多次触发 $stateChangeStart。
app.js 运行部分:
.run(['$rootScope', '$window', '$state', 'authentication', function ($rootScope, $window, $state, authentication) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
event.preventDefault();
authentication.identity()
.then(function (identity) {
if (!authentication.isAuthenticated()) {
$window.location.href = 'external URL';
return;
} else {
$state.go(toState, toParams);
}
});
});
}]);
authentication.factory.js identity() 函数:
function getIdentity() {
if (_identity) {
_authenticated = true;
deferred.resolve(_identity);
return deferred.promise;
}
return $http.get('URL')
.then(function (identity) {
_authenticated = true;
_identity = identity;
return _identity;
}, function () {
_authenticated = false;
});
}
编辑:添加状态:
$stateProvider
.state('site', {
url: '',
abstract: true,
views: {
'feeds': {
templateUrl: 'partials/feeds.html',
controller: 'userFeedsController as userFeedsCtrl'
}
},
resolve: ['$window', 'authentication', function ($window, authentication) {
authentication.identity()
.then(function (identity) {
if (!authentication.isAuthenticated()) {
$window.location.href = 'external URL';
}
})
}]
})
.state('site.start', {
url: '/',
views: {
'container@': {
templateUrl: 'partials/start.html'
}
}
})
.state('site.itemList', {
url: '/feed/{feedId}',
views: {
'container@': {
templateUrl: 'partials/item-list.html',
controller: 'itemListController as itemListCtrl'
}
}
})
.state('site.itemDetails', {
url: '/items/{itemId}',
views: {
'container@': {
templateUrl: 'partials/item-details.html',
controller: 'itemsController as itemsCtrl'
}
}
})
}])
如果您需要更多信息或 app.js 中的更多代码,请告诉我!
【问题讨论】:
-
您已经尝试添加以下行:$locationProvider.html5Mode(true);在您的路线配置中。并将此元数据添加到 html 标头:。这会驱逐 URL 末尾的 uggly /#。
-
哦,是的,我忘记了 html5mode() 记录,谢谢!
标签: javascript angularjs angular-ui-router