简体   繁体   中英

AngularJS Resolve Promise. Redirect if promise is rejected

A little back story.

  • I have public pages, not restricted
  • I have private pages, restricted that require login.
  • I am using Firebase Authentication for the login.

I have my $routeProvider set up in my .config() of my main .module() My restricted paths look like the following.

.when('/admin', {
            controller: 'adminCtrl as admin',
            templateUrl: 'pages/admin/dashboard.tpl.html',
            resolve: {
                "currentAuth": ["$firebaseAuth", function($firebaseAuth) {
                    //$requireAuth returns a promise if authenticated, rejects if not
                    var ref = new Firebase(fbUrl);
                    var authObj = $firebaseAuth(ref);

                    return authObj.$requireAuth();
                }]
            }
        })

My question is about the resolve specifically, I am assuming it is working correctly because I am not seeing the templateUrl on my browser. (I know this for a fact, I removed the return and placed return true and my templateUrl appeared)

So right now, this promise in the resolve is getting rejected. Since I am not a logged in user.

My question is, how would I either a. send $routeProvider to my .otherwise route or b. place a redirect in the resolve if the promise is rejected.

Basically, If the user is not logged in, I want them sent back to the home page. Right now the browser is just showing a blank page.

After some more research (I realize now I needed to dig more, sorry won't happen again.)

I have found a solution by adding .run() to my application.

.run(function($rootScope, $location) {
    $rootScope.$on("$routeChangeError", function(event, current, previous, eventObj) {
        console.log(eventObj);
        if (eventObj === 'AUTH_REQUIRED') {
            $location.path("/");
        }
    });
})

This grabs my routeChangeError and redirects when I have the error of AUTH_REQUIRED.

Simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM