Delvin Defoe
Delvin Defoe

Reputation: 91

Forward to a specific page after logging in

I have an Angular app in which a user is redirected to the login page if they try to access a page for which they need to be authenticated. Currently, when the user is successfully authenticated from the login page, they are redirected to a default start page. The change that I need to make is this:

When a user is attempting to browse to a specific page and needs to login, after the user has successfully logged in, the site should forward the user to the page they wanted.

Any ideas on how this can be done in AngularJS?

Upvotes: 1

Views: 1277

Answers (1)

Delvin Defoe
Delvin Defoe

Reputation: 91

OK, after some research I was able to come up with the solution below:

In app.js I added the following run method.

angular.module('MainModule', [])
...
.run(function($rootScope, $location, UserService) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) {
        if ((!UserService.isUserLoggedIn()) && ($location.path() !== '/login')) {
            $rootScope.postLoginRoute = $location.path();
            $location.path('/login').replace();
        }
    });
});

In my loginController I was able to redirect the user to the page they desire as follows:

function loginController($scope, $location, UserService, $rootScope){  
    $scope.submit = function() {
        if(UserService.validateCredentials($scope.username, $scope.password)){
            if($rootScope.postLoginRoute){
                $location.url($rootScope.postLoginRoute);
            } else{
                $location.path('/defaultPage');
            }
            $rootScope.postLoginRoute = null;
        }
    }
};

Upvotes: 2

Related Questions