问题
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
回答1:
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
回答2:
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');
}
});
来源:https://stackoverflow.com/questions/49302009/angular-js-redirect-to-page-within-module-config