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屋!