我希望我的应用将未登录的用户发送到登录页面。根据流行的答案,该应用程序监视routeChangeStart,如下所示:
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if ($rootScope.currentUser === null) {
var allowPublic = ["partials/logIn.html", "partials/start.html"];
var allowed = _.contains(allowPublic, next.templateUrl);
if (!allowed) {
$location.path("/logIn").replace();
}
}
});
此逻辑正确运行,但更改$ location.path不起作用。 浏览器中的地址栏更改为/ logIn,但视图仍显示不允许的部分。有人知道为什么吗?
我的路线设置如下:
$routeProvider.when('/start', {templateUrl: 'partials/start.html', controller: 'StartController'});
$routeProvider.when('/logIn', {templateUrl: 'partials/logIn.html', controller: 'LogInController'});
$routeProvider.when('/restricted', {templateUrl: 'partials/restricted.html', controller: 'RestrictedController'});
起始页面控制器有时会尝试导航到受限制的页面,如下所示:
// in StartController
$scope.pressedButton = function() {
$location.path('/restricted');
// I'd like to catch this and redirect using the previous logic if user is not logged in
};
答案 0 :(得分:0)
如果将来有人遇到这个问题,这就是我的所作所为,但我不能说我完全理解为什么必须这样做。修复是在超时中包装位置更改。
if (!allowed) {
$timeout(function() {
$location.path("/logIn").replace();
}, 0);
}
它认为问题出现是因为我的代码试图在收听位置更改时尝试更改位置,从而导致回归(然后由于第二次调用是针对允许的位置而暂停) 。通过将路径更改包装在$ timeout中,我想我在强制重定向之前让第一个位置更改完毕。
我对此并不是100%肯定,但我得出的结论是以编程方式阅读"触发事件"第in this angular doc节。
我猜这是明智的,但我想知道为什么我读过的许多路线安全解决方案并没有提到这种危险。 (e.g. see the massively up-voted answer here)。