Javascript 角度更改位置更改路径,但浏览器转到错误页面

Javascript 角度更改位置更改路径,但浏览器转到错误页面,javascript,angularjs,Javascript,Angularjs,我希望我的应用程序将未登录的用户发送到登录页面。根据这里的一个流行答案,该应用程序监视routeChangeStart,如下所示: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.currentUser === null) { var allowPublic = ["partials/logIn.html", "partials/start.html"]

我希望我的应用程序将未登录的用户发送到登录页面。根据这里的一个流行答案,该应用程序监视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();
        }
    }
});
$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'});
此逻辑运行正常,但更改$location.path无效。浏览器中的地址栏更改为/logIn,但视图仍显示不允许的部分内容。有人知道为什么吗

我的路线设置如下:

$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();
        }
    }
});
$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
};

如果将来有人遇到这种情况,我会这么做,尽管我不能说我完全理解为什么我必须这么做。修复方法是在超时时包装位置更改

        if (!allowed) {
            $timeout(function() {
                $location.path("/logIn").replace();
            }, 0);
        }
它认为问题的出现是因为我的代码在侦听位置更改时试图更改位置,导致回归,然后由于第二个调用是针对允许的位置而停止。通过将路径更改包装在$timeout中,我想我是让第一个位置更改在强制重定向之前完成

我不是100%确定这一点,但我是通过以编程方式阅读触发事件一节得出结论的

我想这是明智的,但我想知道为什么我读到的许多路由安全解决方案没有提到这种危险