How to redirect in a ui-router resolver?

前端 未结 7 704
我寻月下人不归
我寻月下人不归 2021-02-03 17:58

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.

7条回答
  •  礼貌的吻别
    2021-02-03 18:52

    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 here.

    UPD: updated code and added plunkr. Looks like it only works if you put it inside a timeout function.

提交回复
热议问题