我正在尝试使用规则函数设置.otherwise()来确定默认URL。由于应用程序尚未加载,我无法注入状态或读取路径,我真正需要做的是在.otherwise()中进行类似的解析,以检查我的UserService并在服务器上ping会话,因为我的UserService.isLoggedIn未定义。在你真正需要解决的地方,你如何处理不同的默认URL?
看看官方文档中的示例:http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.$urlRouterProvider#方法_否则
// Example of using function rule as param
$urlRouterProvider.otherwise(function ($injector, $location) {
return '/a/valid/url';
});
你有$injector
和$location
,所以你可以获得你需要的任何东西。如果你想的话,你甚至可以把它包装在一个易于阅读的可注射功能中:
function myOtherwiseFunction($state, UserService, Whatever) {
// check some $state stuff
if ($state.current) { /* blah */ }
// check some Whatever stuff
if (Whatever.myFancyLogic()) { /* blah */ }
if (UserService.isLoggedIn())
return "/app";
else
return "/login";
}
$urlRouterProvider.otherwise(function ($injector, $location) {
return $injector.invoke(myOtherwiseFunction);
});
您可以在其他函数中调用函数isLogged。
但是。。。问题是,您不能在配置函数中注入服务UserService(我想有一点),因为它不是常量,也不是提供者。
您可以做的是在一个常量中调用日志记录过程,该常量返回类似解析函数的promise:
.constant('login', function(){
var access = function(UserService){
return $q.when('start').then(function(){
return UserService.initSession(); // I suppose you have a similar function
})
}
access.$inject = ['UserService'];
return access;
})
在您的配置函数中:
.config([..., 'login',
...
$urlRouterProvider.otherwise(function() {
login();
...