Divert to alternate homepage if user is not logged in using UI-Router & AngularJS

后端 未结 4 1619
暗喜
暗喜 2020-12-17 06:59

I would like to have two home pages, the first would be for users who have not logged in and the second for users that are logged in.

This is my current set up:

4条回答
  •  一个人的身影
    2020-12-17 07:12

    Just wanted to show, how we can manage authentication driven access to states. Based on this answer and its plunker, we can enrich each state (which should be accessible only for authenticated users) with a data setting, explained here: Attach Custom Data to State Objects (cite:)

    You can attach custom data to the state object (we recommend using a data property to avoid conflicts)...

    So let's have some states with public access:

    // SEE no explicit data defined
    .state('public',{
        url : '/public',
        template : '
    public
    ', }) // the log-on screen .state('login',{ url : '/login', templateUrl : 'tpl.login.html', controller : 'UserCtrl', }) ...

    And some with private access:

    // DATA is used - saying I need authentication
    .state('some',{
        url : '/some',
        template : '
    some
    ', data : {requiresLogin : true }, // HERE }) .state('other',{ url : '/other', template : '
    other
    ', data : {requiresLogin : true }, // HERE })

    And this could be hooked on on the state change:

    .run(['$rootScope', '$state', 'User', function($rootScope, $state, User)
    {
    
      $rootScope.$on('$stateChangeStart'
        , function(event, toState, toParams, fromState, fromParams) {
    
        var isAuthenticationRequired =  toState.data 
              && toState.data.requiresLogin 
              && !User.isLoggedIn
          ;
    
        if(isAuthenticationRequired)
        {
          event.preventDefault();
          $state.go('login');
        }
      });
    }])
    

    See all that in action here

    There is similar Q & A were I try to show the concept of redirecting Authenticated and Not Authenticated user:

    • Angular UI Router: nested states for home to differentiate logged in and logged out

    maybe that could help to get some idea, how we can use ui-router, and its event '$stateChangeStart' to hook on our decision manager - and its forced redirecting...

提交回复
热议问题