Display conditional page when application is opened for the first time

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

This is what I still have:

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');
    }

});

}]);

I assumed that if fromState.urlset to ^, then the application starts for the first time.

For some reason, this code introduces an infinite loop, and I gt - this stack: enter image description here

Now from what I can say, this happened because the if event $state.go('login')receives execution toState.urlalways 404 .

I was hoping that if $state.go('login')it was completed, it toState.urlwould be installed to log in and this call would no longer be completed.

...

- , Angular?

+4
2

plunker, :

codeArtApp.run(['$state', '$rootScope',
 function($state, $rootScope, $log) {

  $rootScope.$on('$stateChangeStart', 
    function(event, toState, toParams, fromState) {

      // instead of 
      // toState.url !== 'login'
      // we compare 
      // toState.name !== 'login'
      var shouldLogin = fromState.url === '^' 
              && toState.name !== 'login';

      if(shouldLogin)
      {
        // this way we stop current execution
        event.preventDefault();
        // and navigate to login
        $state.go('login');  
      }
    });
 }
]);

toState.url URL-, .. '/login' 'login'. : State Change Events, event.preventDefault();. plunker, ...

+3

$urlRouterProvider.otherwise . - :

$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');    
    }

});

, !

+7

Source: https://habr.com/ru/post/1545536/


All Articles