使用AngularJS中的ui-router处理$ requireAuth中的错误

时间:2015-12-28 10:23:46

标签: angularjs authentication ionic-framework firebase angularfire

我有一个经过身份验证的应用程序,我正在尝试处理应用程序首次加载时未经授权的重定向状态。我在调试控制台中注意到,应用程序多次处理未经授权的循环,在最终重定向到我想要的登录页面之前大约5到6次失败。有人可以帮我弄清楚我需要在哪里正确处理这个错误吗?感谢。

我的app.js文件是:

    // Ionic Starter App

// angular.module is a global place for creating, registering and retrieving
// Angular modules 'starter' is the name of this angular module example (also
// set in a <body> attribute in index.html) the 2nd parameter is an array of 
// 'requires'.'starter.controllers' is found in controllers.js
angular.module('starter', 
  ['ionic', 'starter.constants', 'starter.services', 'starter.controllers'])

.run(function($ionicPlatform, $rootScope, $state, $ionicLoading) {
  $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.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);

    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });

  $rootScope.$on("$stateChangeError", 
    function(event, toState, toParams, fromState, fromParams, error) {
  // We can catch the error thrown when the $requireAuth promise is rejected
  // and redirect the user back to the home page
    if (error === "AUTH_REQUIRED") {
      $state.go('app.login');
      //console.log("This isn't working the way I want it to.");
      //login();
    } 
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    controller: 'AppCtrl'
  })

  .state('app.search', {
    url: '/app/search',
    views: {
      'menuContent': {
        templateUrl: 'templates/search.html'
      }
    }
  })

  .state('app.browse', {
    url: '/browse',
    views: {
      'menuContent': {
        templateUrl: 'templates/browse.html'
      }
    }
  })

  .state('app.login', {
    url: '/login',
    views: {
      'menuContent': {
        templateUrl: 'templates/login.html',
        controller: 'LoginCtrl'
      }
    }
  })

  .state('app.list', {
    url: '/list',
    views: {
      'menuContent': {
        templateUrl: 'templates/list.html',
        controller: 'ListCtrl',
        resolve:{
          full_list: function(ListService){
            return ListService.listAll();
          },
          current_Auth: function(LoginService){
            return LoginService.getAuthObject().$requireAuth();
          }
        }
      }
    }
  })

  .state('app.detail', {
    url: '/list/:itemId',
    views: {
      'menuContent': {
        templateUrl: 'templates/detail.html',
        controller: 'DetailCtrl',
        resolve:{
          list_item: function($stateParams, ListService){
            return ListService.itemDetail($stateParams.itemId);
          },
          current_Auth: function(LoginService){
            return LoginService.getAuthObject().$requireAuth();
          }
        }
      }
    }
  });
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/list');
});

我的controllers.js文件如下:

angular.module('starter.controllers', [])

.controller('AppCtrl', function($scope, $state, LoginService) {

  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //$scope.$on('$ionicView.enter', function(e) {
  //});
  $scope.userLoggedIn= LoginService.getAuthObject().$getAuth();

  $scope.logout=function(){
    $state.go('app.login');
    LoginService.getAuthObject().$unauth();
  }
})

.controller('LoginCtrl', function($state, $scope, $timeout, LoginService){
  $scope.loginData={};

  $scope.doLogin = function(){
    LoginService.authenticateUser($scope.loginData, 
      function(err, authData){
        if (err){
          console.log("Login failed!");
          return;
        }
        //$location.path('/app/list');
        $state.go('app.list');
      });
  };

  $scope.logout = function(){
    $state.go('app.login');
    LoginService.getAuthObject().$unauth();
    // $state.go('app.login');
  };
})

.controller('ListCtrl', function($state, $scope, full_list, current_Auth) {
  $scope.list = full_list;

  $scope.goToAccount=function(){
    $state.go('app.login');
  };
})

.controller('DetailCtrl', function($scope, $state, list_item, current_Auth) {
  $scope.item = list_item;

  $scope.goToAccount=function(){
    $state.go('app.login');
  };
});

我的services.js如下:

angular.module('starter.services', ['firebase'])

.factory('LoginService', function($firebaseAuth){

    var ref = new Firebase('https://db-hidden-here.firebaseIO.com');

    return {
        authenticateUser: function (user, cb) {
            return ref.authWithPassword({
                email: user.username,
                password: user.password
                }, function(error, authData) {
                if (error) {
                    //Login failed
                    cb(error);
                } else {
                    cb(null, authData);
                }
            });
        },

        getAuthObject: function(){
            return $firebaseAuth(ref);
        }        
    };
})

.factory('ListService', function($q, $firebaseArray, $firebaseObject) {

    var refList = 
    new Firebase('https://db-hidden-here.firebaseIO.com/coupons');

    return {
        listAll: function() {
            var deferred = $q.defer();
            var items = $firebaseArray(refList);
            deferred.resolve(items);
            return deferred.promise;
        },

        itemDetail: function(key) {
            var deferred = $q.defer();
            var itemRef = refList.child(key);
            var item = $firebaseObject(itemRef);
            deferred.resolve(item);
            return deferred.promise;
        }
    };
});

这是我的调试输出:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D
    at ionic.bundle.js:8900
    at Scope.$digest (ionic.bundle.js:24553)
    at Scope.$apply (ionic.bundle.js:24783)
    at bootstrapApply (ionic.bundle.js:10465)
    at Object.invoke (ionic.bundle.js:13282)
    at doBootstrap (ionic.bundle.js:10463)
    at bootstrap (ionic.bundle.js:10483)
    at angularInit (ionic.bundle.js:10377)
    at ionic.bundle.js:37191
    at HTMLDocument.trigger (ionic.bundle.js:11828)(anonymous function) @ ionic.bundle.js:21162(anonymous function) @ ionic.bundle.js:17941Scope.$apply @ ionic.bundle.js:24785bootstrapApply @ ionic.bundle.js:10465invoke @ ionic.bundle.js:13282doBootstrap @ ionic.bundle.js:10463bootstrap @ ionic.bundle.js:10483angularInit @ ionic.bundle.js:10377(anonymous function) @ ionic.bundle.js:37191trigger @ ionic.bundle.js:11828eventHandler @ ionic.bundle.js:12103
ionic.bundle.js:8900 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D(anonymous function) @ ionic.bundle.js:8900Scope.$digest @ ionic.bundle.js:24553Scope.$apply @ ionic.bundle.js:24783bootstrapApply @ ionic.bundle.js:10465invoke @ ionic.bundle.js:13282doBootstrap @ ionic.bundle.js:10463bootstrap @ ionic.bundle.js:10483angularInit @ ionic.bundle.js:10377(anonymous function) @ ionic.bundle.js:37191trigger @ ionic.bundle.js:11828eventHandler @ ionic.bundle.js:12103
ionic.bundle.js:21162 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D
    at ionic.bundle.js:8900
    at Scope.$digest (ionic.bundle.js:24553)
    at Scope.$apply (ionic.bundle.js:24783)
    at done (ionic.bundle.js:19196)
    at completeRequest (ionic.bundle.js:19368)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:19309)(anonymous function) @ ionic.bundle.js:21162(anonymous function) @ ionic.bundle.js:17941Scope.$apply @ ionic.bundle.js:24785done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:8900 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D(anonymous function) @ ionic.bundle.js:8900Scope.$digest @ ionic.bundle.js:24553Scope.$apply @ ionic.bundle.js:24783done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:21162 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D
    at ionic.bundle.js:8900
    at Scope.$digest (ionic.bundle.js:24553)
    at Scope.$apply (ionic.bundle.js:24783)
    at done (ionic.bundle.js:19196)
    at completeRequest (ionic.bundle.js:19368)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:19309)(anonymous function) @ ionic.bundle.js:21162(anonymous function) @ ionic.bundle.js:17941Scope.$apply @ ionic.bundle.js:24785done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:8900 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D(anonymous function) @ ionic.bundle.js:8900Scope.$digest @ ionic.bundle.js:24553Scope.$apply @ ionic.bundle.js:24783done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:21162 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D
    at ionic.bundle.js:8900
    at Scope.$digest (ionic.bundle.js:24553)
    at Scope.$apply (ionic.bundle.js:24783)
    at done (ionic.bundle.js:19196)
    at completeRequest (ionic.bundle.js:19368)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:19309)(anonymous function) @ ionic.bundle.js:21162(anonymous function) @ ionic.bundle.js:17941Scope.$apply @ ionic.bundle.js:24785done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:8900 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D(anonymous function) @ ionic.bundle.js:8900Scope.$digest @ ionic.bundle.js:24553Scope.$apply @ ionic.bundle.js:24783done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:21162 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D
    at ionic.bundle.js:8900
    at Scope.$digest (ionic.bundle.js:24553)
    at Scope.$apply (ionic.bundle.js:24783)
    at done (ionic.bundle.js:19196)
    at completeRequest (ionic.bundle.js:19368)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:19309)(anonymous function) @ ionic.bundle.js:21162(anonymous function) @ ionic.bundle.js:17941Scope.$apply @ ionic.bundle.js:24785done @ ionic.bundle.js:19196completeRequest @ ionic.bundle.js:19368requestLoaded @ ionic.bundle.js:19309
ionic.bundle.js:8900 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.3/$rootScope/infdig?p0=10&p1=%5B%5D

请帮助我找出我需要处理此错误循环的位置以及如何最好地执行此操作。感谢。

1 个答案:

答案 0 :(得分:2)

也许还有更多内容,但在您$stateChangeError event.preventDefault(); $state.go('app.login')之前$UrlRouter,以防止$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { // We can catch the error thrown when the $requireAuth promise is rejected // and redirect the user back to the home page if (error === "AUTH_REQUIRED") { event.preventDefault(); $state.go('app.login'); //console.log("This isn't working the way I want it to."); //login(); } }); 将网址还原到之前的有效位置< / p>

webViewToPrint.setDrawingCacheEnabled(true);