简体   繁体   English

角度更改位置更改了路径,但浏览器进入了错误的页面

[英]Angular change location changes path but browser goes to wrong page

I'd like my app to send non-logged in users to a login page. 我希望我的应用程序将未登录的用户发送到登录页面。 Based on a popular answer here, the app watches for routeChangeStart, like this: 根据此处的一个流行答案,该应用会监视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();
        }
    }
});

This logic runs correctly, except that changing $location.path doesn't work. 此逻辑正确运行,除了更改$ location.path不起作用。 The address bar in the browser changes to /logIn, but the view still shows the non-permitted partial . 浏览器中的地址栏更改为/ logIn,但视图仍显示不允许的partial Does anybody have an idea why? 有人知道为什么吗?

My routes are setup like this: 我的路线设置如下:

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

The start page controller sometimes tries to navigate to the restricted page, like this: 起始页控制器有时会尝试导航到受限页面,如下所示:

// 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
};

In case someone comes across this in the future, here's what I did, though I can't say I fully understand why I had to do it. 万一将来有人遇到这个问题,这就是我所做的,尽管我不能说我完全理解为什么必须这样做。 The fix was to wrap the location change in a timeout. 解决方法是将位置更改打包为超时。

        if (!allowed) {
            $timeout(function() {
                $location.path("/logIn").replace();
            }, 0);
        }

It think the problem arose because my code was trying to change the location while it's listening for location changes, leading to a regress (which is then halted by the fact that the second call is for a permitted location). 它认为出现问题是因为我的代码在侦听位置更改时试图更改位置,从而导致回归(然后由于第二次调用是针对允许的位置而被暂停)。 By wrapping the path change in $timeout, I guess I'm letting the first location change finish before forcing the redirect. 通过将路径更改包装在$ timeout中,我想我要在强制重定向之前先完成第一个位置更改。

I'm not 100% sure about this, but I came to the conclusion reading the "Triggering Events Programmatically" section in this angular doc . 我对此不是100%的确定,但是我在阅读这份有角度的文档中的编程方式触发事件”一节得出了结论。

This is sensible, I guess, but I wonder why the many route security solutions I read about didn't mention this danger. 我猜这是明智的,但是我不知道为什么我读过的许多路由安全解决方案都没有提到这种危险。 ( eg see the massively up-voted answer here ). 例如,请在此处查看投票人数最多的答案 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM