繁体   English   中英

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

[英]Angular JS redirect to page within module config

我有一个角度js模块,其中设置了所有路由。 我定义了一个变量“维护”。 如果将其设置为true,那么我希望将该页面重定向到维护页面。 我已经使用stateprovider设置了状态。

我正在尝试使用以下代码进行重定向-

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

这似乎不起作用。 但是,如果我执行以下操作,则重定向成功-

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

我认为在这种情况下,使用“否则”可能不是正确的解决方案。 如何重定向?

编辑

在下面的示例中,我希望将对app.html的任何调用都重定向到维护页面,而不考虑#之后的内容。

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

您不能在config方法中使用状态服务,因为此时仍在配置状态服务。

如果您想在运行angular模块后立即进行特定的重定向,则可以在.run函数中执行$ state.go,如下所示:

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

或者更好的是,您可以使用过渡服务在每次状态过渡后强制进行重定向:

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

您不能在configure方法中使用状态服务。 相反,如果您想在加载角度模块后重定向到某个状态,则可以使用.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