Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Page Display when application opens for the first time

Hi I am just starting to learn angular && angular-ui-router and am trying to figure out how to determine when the app is opened for the first time to send the user to the login page or home page.

This is what i have so far:

codeArtApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
    .state('login',{
        url : '/login',
        templateUrl:'App/scripts/login/loginView.html',
        controller: 'loginCtrl'
    })
    .state('profile', {
        url : '/profile',
        templateUrl:'App/scripts/login/loginView.html',
        controller: 'profileCtrl'
    })
    .state('404', {
        url: '/404',
        templateUrl:'App/scripts/views/404.html'
    });


$urlRouterProvider.otherwise("404");

});

codeArtApp.run(['$state', '$rootScope', function($state, $rootScope, $log){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
    if(fromState.url === '^' && toState.url !== 'login'){
        $state.go('login');
    }

});

}]);

What I assumed here is that if fromState.url is set to ^ then the application is starting for the first time.

For some reason this code enters an infinite loop and I gt this stacktrace: enter image description here

Now from what I can tell this happened because event if $state.go('login') gets execute toState.url is always 404.

I had hoped if $state.go('login') gets executed toState.url would have been set to login and that call would not be executed anymore.

I may not be setting this logic in the right place...

Can anyone tell me how conditionaly page displayed is achieved in Angular?

like image 453
aleczandru Avatar asked Dec 25 '22 07:12

aleczandru


1 Answers

In your $urlRouterProvider.otherwise call you can pass a function instead of a string. Something like this:

$urlRouterProvider.otherwise(function($injector){

    var $state = $injector.get('$state');
    var Storage = $injector.get('Storage');

    if (Storage.has('authToken')) {
        $state.go('home');
    }
    else {
        $state.go('login');    
    }

});

Hope this helps!

like image 126
sean-hill Avatar answered Jan 30 '23 21:01

sean-hill