Angular JS重定向到模块配置内的页面 [英] Angular JS redirect to page within module config
问题描述
我有一个angular js模块,其中设置了所有路由.我定义了一个变量维护".如果将其设置为true,那么我希望将该页面重定向到维护页面.我已经使用stateprovider设置了状态.
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?
编辑
在下面的示例中,我希望将对app.html的任何调用都重定向到维护页面,而不考虑#之后的内容.
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
推荐答案
您不能在config方法中使用状态服务,因为此时仍在配置状态服务.
You cannot use the state service within the config method since it is still being configured at that point.
如果要在运行angular模块后立即进行特定的重定向,则可以在.run函数中执行$ state.go,如下所示:
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
这篇关于Angular JS重定向到模块配置内的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!