简体   繁体   中英

Angular JS redirect to page within module config

I have an angular js module where all the routes are setup. I have defined a variable "maintenance". if this is set to true , I want the page to be redirected to maintenance page. I have setup the states using 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 #.

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.

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.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

You cannot use the state service within a configure method. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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