How to handle states when logged in (Ionic, Firebase, AngularJS)?

后端 未结 3 1682
既然无缘
既然无缘 2021-02-05 11:06

I am building an app in Ionic and have started to dig into the Firebase Authentication method. So far I have managed to setup a Login through Twitter properly (I can login and l

3条回答
  •  我寻月下人不归
    2021-02-05 11:30

    You are almost there. All you need is to ensure your states are marked appropriate with the custom property 'AuthRequired' and listen for $stateChangeStart event to check for authentication. This event fires each time you move with in the application.

    .run(function($ionicPlatform, AuthService) {
          //ionic init code    
    
          //stateChange event
          $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
          if (toState.authRequired && !AuthService.isAuthenticated()){ //Assuming the AuthService holds authentication logic
            // User isn’t authenticated
            $state.transitionTo("login");
            event.preventDefault(); 
          }
        });
    }
    
    .state('tab.dash', {
        url: '/dash',
        views: {
          'tab-dash': {
            templateUrl: 'templates/tab-dash.html',
            controller: 'DashCtrl',
            authRequired: true
          }
        }
      })
    
      .state('tab.chats', {
          url: '/chats',
          views: {
            'tab-chats': {
              templateUrl: 'templates/tab-chats.html',
              controller: 'ChatsCtrl',
              authRequired: true
            }
          }
        })
    

    The best place to have $stateChangeStart event handler would be the app run.

提交回复
热议问题