简体   繁体   English

Angular JS重定向到模块配置内的页面

[英]Angular JS redirect to page within module config

I have an angular js module where all the routes are setup. 我有一个角度js模块,其中设置了所有路由。 I have defined a variable "maintenance". 我定义了一个变量“维护”。 if this is set to true , I want the page to be redirected to maintenance page. 如果将其设置为true,那么我希望将该页面重定向到维护页面。 I have setup the states using stateprovider. 我已经使用stateprovider设置了状态。

I am trying to redirect using the code below - 我正在尝试使用以下代码进行重定向-

if(maintenance){
    $state.go('maintenance');
}

This doesn't seem to work. 这似乎不起作用。 However If I do the below , the redirect is successful - 但是,如果我执行以下操作,则重定向成功-

   $urlRouterProvider.otherwise('/signup/productSelector');

I assume using "otherwise" may not be the correct solution in this case. 我认为在这种情况下,使用“否则”可能不是正确的解决方案。 How can I redirect? 如何重定向?

EDIT 编辑

In the below example , I would like any call to app.html to be redirected to maintenance page irrespective of what is present after #. 在下面的示例中,我希望将对app.html的任何调用都重定向到维护页面,而不考虑#之后的内容。

https://<url>/app.html#/orders/resi

You cannot use the state service within the config method since it is still being configured at that point. 您不能在config方法中使用状态服务,因为此时仍在配置状态服务。

If you'd like to specificly redirect right after the angular module is run then you could execute the $state.go in a .run function as follows: 如果您想在运行angular模块后立即进行特定的重定向,则可以在.run函数中执行$ state.go,如下所示:

angular.module("yourModule").run(['$state', function($state) {
    $state.go('maintenance');
}])

Or better yet you can force the redirection to happen after every state transition using the transition services: 或者更好的是,您可以使用过渡服务在每次状态过渡后强制进行重定向:

angular.module("yourModule").run(['$transition', function($transition) {
    $transition.onBefore({}, function(transition) {
        var stateService = transition.router.stateService;
        if (maintenance && transition.to().name !== 'maintenance') {
            return stateService.target('maintenance');
        }
    })
}])

https://ui-router.github.io/guide/transitionhooks https://ui-router.github.io/guide/transitionhooks

You cannot use the state service within a configure method. 您不能在configure方法中使用状态服务。 Instead if you'd like to redirect to a certain state after the angular module has been loaded you could do it in a .run function insteadn 相反,如果您想在加载角度模块后重定向到某个状态,则可以使用.run函数代替

angular.module().run(['$state' '$rootScope', function($state, $rootScope) {
    $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {

    if (maintanance) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
         $state.go('maintenance');
    } 
});

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

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