简体   繁体   English

角度重定向以阻止路线

[英]Angular redirect for blocked route

I want to block certain routes when a user has not accepted an agreement, etc. Using $locationChangeStart works pretty well: 我想在用户未接受协议等时阻止某些路由。使用$locationChangeStart效果很好:

$scope.$on('$locationChangeStart', function(event, newVal, oldVal) {        
    var targetPage = newVal.substring(newVal.lastIndexOf("/") + 1);

    if (!acceptedRelease && targetPage != "") {
        event.preventDefault();
        $location.path("/");
    }
});

This works fine as long as the initial page is loaded with the route / (ie empty). 只要初始页面加载了路由/ (即为空),此方法就可以正常工作。 However, if you load the page with /mainMenu or the like, it does not work. 但是,如果使用/mainMenu或类似内容加载页面,则该页面不起作用。 The route itself is blocked via event.preventDefault() , but $location.path does not fire/redirect appropriately. 路由本身已通过event.preventDefault()阻止,但$location.path无法正确触发/重定向。 Using 使用

$scope.$apply(function () { $location.path("/"); })

does not work either. 也不起作用。 I get an error $digest already in progress . 我收到一个错误$digest already in progress

Is there any way to redirect after blocking a route in $locationChangeStart ? $locationChangeStart阻止路由后,是否可以重定向?

In general, is there any way to block certain routes in Angular and perform redirects when the routes have been blocked? 通常,有什么方法可以在Angular中阻止某些路由并在路由被阻止时执行重定向?

You could try something like this in you routeChangeSuccess: 您可以在routeChangeSuccess中尝试以下操作:

$rootScope.$on('$routeChangeSuccess',function(){
    if(!acceptedTermsVar){
      $location.path('/wherever-you-want');
    }
});

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

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