[英]Angular JS redirect to page within module config
我有一個角度js模塊,其中設置了所有路由。 我定義了一個變量“維護”。 如果將其設置為true,那么我希望將該頁面重定向到維護頁面。 我已經使用stateprovider設置了狀態。
我正在嘗試使用以下代碼進行重定向-
if(maintenance){
$state.go('maintenance');
}
這似乎不起作用。 但是,如果我執行以下操作,則重定向成功-
$urlRouterProvider.otherwise('/signup/productSelector');
我認為在這種情況下,使用“否則”可能不是正確的解決方案。 如何重定向?
編輯
在下面的示例中,我希望將對app.html的任何調用都重定向到維護頁面,而不考慮#之后的內容。
https://<url>/app.html#/orders/resi
您不能在config方法中使用狀態服務,因為此時仍在配置狀態服務。
如果您想在運行angular模塊后立即進行特定的重定向,則可以在.run函數中執行$ 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');
}
})
}])
您不能在configure方法中使用狀態服務。 相反,如果您想在加載角度模塊后重定向到某個狀態,則可以使用.run函數代替
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');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.