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

后端 未结 3 1665
既然无缘
既然无缘 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:29

    I had the same problem that yours! Take a look how I solved it!

    app.js

    angular.module('app', ['ionic','firebase', 'app.controllers', 'app.routes', 'app.directives','app.services','app.filters',])
    
    .run(function($ionicPlatform, $rootScope, $state) {
      $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
          cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
          cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {//
          // org.apache.cordova.statusbar required
          StatusBar.styleDefault();
        }
      });
    
      //stateChange event
      $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
        var user = firebase.auth().currentUser;
        if (toState.authRequired && !user){ //Assuming the AuthService holds authentication logic
          // User isn’t authenticated
          $state.transitionTo("login");
          event.preventDefault(); 
        }
      });
      // Initialize Firebase Here
    
    })
    

    routes.js

    angular.module('app.routes', ['ionicUIRouter'])
    
    .config(function($stateProvider, $urlRouterProvider) {
    
      $stateProvider  
    
      .state('login', {
        url: '/login',
        templateUrl: 'templates/login.html',
        controller: 'loginCtrl'
      })
    
     .state('menu', {
        url: '/menu',
        templateUrl: 'templates/menu.html',
        abstract:true,
        controller: 'menuCtrl'
      })
    
      .state('menu.dash', {
        url: '/contas',
        templateUrl: 'templates/dash.html',
        controller: 'contasCtrl',
        authRequired: true
      })
    
    $urlRouterProvider.otherwise('/login')
    
    });
    

提交回复
热议问题