我正在使用ui-router 1.0.3在Angular 1.5.8中创建一个应用程序。 Ui路由器的钩子很棒但它们不能用于浏览器重新加载。
以下是我的配置块,用于注册状态:
(function(app) {
'use strict';
app.config(configFn);
configFn.$inject = ['$stateProvider'];
function configFn($stateProvider) {
$stateProvider
.state('login', {
url: '/login',
component: 'loginComponent'
})
.state('selfcare', {
url: '/',
component: 'selfCareComponent',
abstract: true
})
.state('selfcare.dashboard', {
url: 'dashboard',
component: 'dashboardComponent'
})
.state('selfcare.appHome', {
url: 'appHome/:id',
component: 'appHomeComponent'
})
.state('selfcare.serviceHome', {
url: 'serviceHome/:id',
component: 'serviceHomeComponent'
})
}
})(angular.module('selfcare'));
以下是用于在转换上注册挂钩的运行块:
(function(app) {
'use strict';
app.run(runFn);
runFn.$inject = ['$rootScope', '$transitions' ,'$localStorage'];
function runFn($rootScope, $transitions, $localStorage) {
$transitions.onStart({to:'**'}, function(transtion){
$rootScope.ngProgress.start();
})
$transitions.onSuccess({to:'**'}, function(transtion){
$rootScope.ngProgress.complete();
})
$transitions.onBefore({to:'login'}, function(transtion){
if($localStorage.isLoggedIn > Date.now()){
return transtion.router.stateService.target('selfcare.dashboard');
}
})
$transitions.onBefore({to:'selfcare.**'}, function(transtion){
if(!$localStorage.isLoggedIn || $localStorage.isLoggedIn < Date.now()){
$localStorage.$reset();
return transtion.router.stateService.target('login');
}
})
}
})(angular.module('selfcare'));
我无法弄清楚我在哪里做错了。一旦应用程序稳定并且正常工作,就会调用挂钩但是在浏览器重新加载时我可以打开任何URL并且不会调用任何挂钩。
任何帮助将不胜感激。感谢
答案 0 :(得分:0)
我设法做了所需要的但我不知道这是否是最好的方法。我想在运行块中写入转换。
作为钩子回调参数的转换对象提供了injector
,可用于在config
应用程序块中获取运行时服务。
(我们也可以在$injector
块中注入config
)
(function(app) {
'use strict';
app.config(configFn);
configFn.$inject = ['$transitionsProvider'];
function configFn($transitionsProvider) {
$transitionsProvider.onStart({ to: '**' }, function(transtion) {
transtion.injector().get('$rootScope').ngProgress.start();
})
$transitionsProvider.onSuccess({ to: '**' }, function(transtion) {
transtion.injector().get('$rootScope').ngProgress.complete();
})
$transitionsProvider.onBefore({ to: 'login' }, function(transtion) {
var $localStorage = transtion.injector().get('$localStorage');
if ($localStorage.isLoggedIn > Date.now()) {
return transtion.router.stateService.target('selfcare.dashboard');
}
})
$transitionsProvider.onBefore({ to: 'selfcare.**' }, function(transtion) {
var $localStorage = transtion.injector().get('$localStorage');
if (!$localStorage.isLoggedIn || $localStorage.isLoggedIn < Date.now()) {
$localStorage.$reset();
return transtion.router.stateService.target('login');
}
})
}
})(angular.module('selfcare'));