Angular JS 重定向到模块配置中的页面
Angular JS redirect to page within module config
我有一个 angular js 模块,其中设置了所有路由。我定义了一个变量"maintenance"。如果设置为 true ,我希望将页面重定向到维护页面。我已经使用 stateprovider 设置了状态。
我正在尝试使用以下代码进行重定向 -
if(maintenance){
$state.go('maintenance');
}
这似乎不起作用。但是,如果我执行以下操作,则重定向成功 -
$urlRouterProvider.otherwise('/signup/productSelector');
我假设在这种情况下使用 "otherwise" 可能不是正确的解决方案。我该如何重定向?
编辑
在下面的示例中,我希望对 app.html 的任何调用都重定向到维护页面,而不管 #.
之后出现的是什么
https://<url>/app.html#/orders/resi
您不能在配置方法中使用状态服务。相反,如果您想在 angular 模块加载后重定向到某个状态,您可以在 .运行 函数中执行此操作而不是
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');
}
});
您不能在配置方法中使用状态服务,因为此时它仍在配置中。
如果你想在 angular 模块是 运行 之后特定地重定向,那么你可以在 .运行 函数中执行 $state.go ,如下所示:
angular.module("yourModule").run(['$state', function($state) {
$state.go('maintenance');
}])
或者更好的是,您可以使用转换服务在每次状态转换后强制进行重定向:
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');
}
})
}])
我有一个 angular js 模块,其中设置了所有路由。我定义了一个变量"maintenance"。如果设置为 true ,我希望将页面重定向到维护页面。我已经使用 stateprovider 设置了状态。
我正在尝试使用以下代码进行重定向 -
if(maintenance){
$state.go('maintenance');
}
这似乎不起作用。但是,如果我执行以下操作,则重定向成功 -
$urlRouterProvider.otherwise('/signup/productSelector');
我假设在这种情况下使用 "otherwise" 可能不是正确的解决方案。我该如何重定向?
编辑
在下面的示例中,我希望对 app.html 的任何调用都重定向到维护页面,而不管 #.
之后出现的是什么https://<url>/app.html#/orders/resi
您不能在配置方法中使用状态服务。相反,如果您想在 angular 模块加载后重定向到某个状态,您可以在 .运行 函数中执行此操作而不是
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');
}
});
您不能在配置方法中使用状态服务,因为此时它仍在配置中。
如果你想在 angular 模块是 运行 之后特定地重定向,那么你可以在 .运行 函数中执行 $state.go ,如下所示:
angular.module("yourModule").run(['$state', function($state) {
$state.go('maintenance');
}])
或者更好的是,您可以使用转换服务在每次状态转换后强制进行重定向:
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');
}
})
}])