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

后端 未结 1 1071
慢半拍i
慢半拍i 2020-12-06 07:42

I\'m starting a new project using boilerplate MEAN provided by MEAN.JS (not .IO).
I\'m new to ui-router and I\'m having trouble figuring out how to accomplish this scena

相关标签:
1条回答
  • 2020-12-06 08:16

    There is a plunker providing behaviour as described above. Firstly, there is a change in a state definition, moving the url from abstract into both child states, and introducing logon state for later checks:

      // Redirect to home view when route not found
      $urlRouterProvider.otherwise('/');
    
      // Home state routing
      $stateProvider.
      state('home', {
        //url: '/',
        abstract: true,
        template: '<div ui-view=""></div>',
      }).
      state('home.loggedOut', {
        url: '/',
        ...
      }).
      state('home.loggedIn', {
        url: '/',
        ...
      })
      .state('logon', {
        url: '/logon',
        templateUrl: 'tpl.logon.html',
        controller: 'LogonCtrl',
      });
    

    What we do have right now, is definition of 2 states, with a same url. The first will be taken as a default.. and used.

    Now, we have to introduce a state change observer, which will redirect to proper sub-state, based on a AuthSvc setting isLoggedIn:

    .run(['$rootScope', '$state', 'AuthSvc', 
     function($rootScope, $state, AuthSvc) {
    
      $rootScope.$on('$stateChangeStart', function(event, toState, toParams
                                                      , fromState, fromParams) {
    
        // logged out is logged out
        var doRedirectToLoggedOut = !AuthSvc.isLoggedIn 
                  && toState.name === "home.loggedIn";
    
        if (doRedirectToLoggedOut) {
            event.preventDefault();
            $state.go("home.loggedOut");
        }
    
        // logged in is logged in
        var doRedirectToLoggedIn = AuthSvc.isLoggedIn 
                  && toState.name === "home.loggedOut";
    
        if (doRedirectToLoggedIn) {
            event.preventDefault();
            $state.go("home.loggedIn");
        }
      });
    }])
    

    As this example shows in action, until we change isLoggedIn (click on logon link) we are redirected to correct sub-state ... even if we would like to see the other

    0 讨论(0)
提交回复
热议问题