如何在ui路由器解析器中重定向? [英] How to redirect in a ui-router resolver?
问题描述
我正在尝试在ui路由器解析器中重定向,并想知道是否有一种方法可以在路由器解析器中进行重新路由.目前,这并不像人们想象的那样.
I am trying to redirect inside a ui-router resolve and wanted to know if there is a way to reroute in a router resolver. Currently this does not work as one would think.
resolver(auth, $state){
if(!auth.isLoggedIn()){
$state.go('noLoggedInPath');
}
}
一个解析器如何正确重定向?
我的临时破解是这个,但我对此不太满意.
My temp hack is this but I am not comfortable with it.
resolver(auth, $state, $timeout){
if(!auth.isLoggedIn()){
$timeout(function () {
$state.go('noLoggedInPath');
}, 0);
}
}
推荐答案
您可以从resolver
函数返回一个Promise,该Prom指示是否继续导航到该状态.如果您决定导航到其他地方-拒绝诺言并指定正确的状态:
You can return a promise from your resolver
function that will indicate whether to continue navigating to the state or not. If you decide to navigate somewhere else - reject the promise and specify the proper state:
resolver($q, $state, $timeout, auth) {
var deferred = $q.defer();
// $timeout is an example; it also can be an xhr request or any other async function
$timeout(function() {
if (!auth.isLoggedIn()) {
// user is not logged, do not proceed
// instead, go to a different page
$state.go('noLoggedInPath');
deferred.reject();
} else {
// everything is fine, proceed
deferred.resolve();
}
});
return deferred.promise;
}
Plunkr 此处.
UPD:更新了代码并添加了plunkr.看起来只有将它放在超时函数中,它才起作用.
UPD: updated code and added plunkr. Looks like it only works if you put it inside a timeout function.
这篇关于如何在ui路由器解析器中重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!