Nebojsa Masic
Nebojsa Masic

Reputation: 53

Execute function before page is rendered

I am using angular.js and I'm trying to check has session been created on server side, and if not I want to redirect to login page.

Problem is that redirection occurs a few second after page is loaded, but I would like to execute function before the page is loaded.

Any suggestions how to achieve this?

Here is my controller:

myPanel.controller('globalController', function($scope, $http){
     $http.get('../classes/login.php').then(function(response){
             $scope.isSession = response.data;
             if($scope.isSession.isStarted === false){
                 window.location = 'http://localhost/PDP/admin';
             }
        });
 });

Upvotes: 2

Views: 2778

Answers (1)

Tarun Dugar
Tarun Dugar

Reputation: 8971

Use run function which is executed before the controllers are configured:

app.run(run)

function run($http) {
    $http.get('../classes/login.php').then(function(response){
         var isSession = response.data;
         if(isSession.isStarted === false){
             window.location = 'http://localhost/PDP/admin';
         }
    });
}

However, this will only run once. Now, if you are using ui-router we can use the $stateChangeStart event to run this function whenever a state changes as follows:

//runs everytime when state changes
function run($rootScope, $http, $state) {
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        //http get function here
    })
} 

Another use case is you want this function to run only for a particular state. In that case, use resolve(again only if you are using ui-router):

.state('state_nam', {
    resolve: {
        access: ['$http', function($http) {
            $http.get('../classes/login.php').then(function(response){
                var isSession = response.data;
                if(isSession.isStarted === false){
                    window.location = 'http://localhost/PDP/admin';
                }
            });
        }] 
    }
})

Upvotes: 4

Related Questions