Angular JS redirect to page within module config

Issue

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

Solution

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

Answered By – bramve

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.