如何在 ui-router 解析器中重定向? [英] How to redirect in a ui-router resolver?

查看:24
本文介绍了如何在 ui-router 解析器中重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 ui-router 解析中重定向,并想知道是否有办法在路由器解析器中重新路由.目前这并不像人们想象的那样工作.

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 函数返回一个承诺,该承诺将指示是否继续导航到状态.如果您决定导航到其他地方 - 拒绝承诺并指定正确的状态:

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-router 解析器中重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆