【问题标题】:Unable to handle error in $stateChange, using ui-router and AngularFire使用 ui-router 和 AngularFire 无法处理 $stateChange 中的错误
【发布时间】:2017-12-15 19:48:57
【问题描述】:

我在我的应用中加入了身份验证,使用的是 Google 的 Firebase。我一直在关注他们的文档https://www.firebase.com/docs/web/libraries/angular/guide/user-auth.html。尽管此方法使用stateChange,但据我所知,ui-router 已弃用此方法。所以在网上看我把我的脚本从这个例子变成了:

app.run(["$rootScope", "$state", function($rootScope, $state) {

    $rootScope.$on("$stateChangeError", 
       function(event, toState, toParams, fromState, fromParams, error) {
            console.log('HELLO')
            if (error === "AUTH_REQUIRED") {
                $state.go("login");
        }
    });
}]);

到:

app.run(($transitions, $state) => {
    $transitions.onError({}, ($transition$) => {
        if ($transition$.$to().name !== 'init' && $transition$.$from().name !== 'error') {
            $state.go("login");
        }
    });
});

我正在尝试处理该错误,因此当用户尝试访问需要身份验证的页面时,它会将他们引导回登录屏幕。第二种方法是有效的,当它尝试将状态更改为 login 时会冻结。

问题

当用户尝试访问需要身份验证的页面时,为什么我的脚本无法将用户重定向到 login 页面?

app.config(['$stateProvider', function($stateProvider, ) {

    $stateProvider
    .state('login', {
        url: '/login',
        component: 'login'
    })
    .state('patents', {
        url: '/patents',
        component: 'patents',
        resolve: {
            currentAuth: function(authentication) {
                return authentication.requireAuth();
            }
     });
}]);


app.factory('authentication', ['$rootScope', '$location', '$firebaseAuth', '$firebaseObject', function($rootScope, $location, $firebaseAuth, $firebaseObject) {

var auth = $firebaseAuth();

//LOAD OF OTHER AUTHENTICATION METHODS

    return {

        requireAuth: function() {
            return auth.$requireSignIn();
        }
    }
}])      

【问题讨论】:

    标签: angularjs firebase angular-ui-router firebase-authentication


    【解决方案1】:

    我有一个类似的用例。我没有时间真正弄清楚您的具体问题的答案,但我可以为您的情况提供解决方案。

    让我们在转换开始之前处理身份验证。

    app.run(["$state", '$transitions', '$q', 'Auth',
        function($state, $transitions, $q, Auth) {
    
      //overrides default error outputting by ui.router
      $state.defaultErrorHandler(function(error) {
        console.error(error);
      });
    
      //redirects to login page if we're not signed in
      $transitions.onBefore({to: 'home.**', from: '**'}, function(trans) {
        var deferred = $q.defer();
    
        Auth.$requireSignIn().then(function() {
          //we're signed in, so proceed to home.**
          deferred.resolve();
        }).catch(function() {
          //we're not signed in and home.** requires authentication
          //so resolve with the state you want to reroute to, refreshing
          //the url w/ reload === true
          var params = { reload: true };
          deferred.resolve($state.target('login', undefined, params));
        });
    
        return deferred.promise;
      });
    
      //redirects to home page if we're signed in
      $transitions.onBefore({to: 'login.**', from: '**'}, function(trans) {
        var deferred = $q.defer();
    
        Auth.$requireSignIn().then(function() {
          //we're signed in, so lets avoid going to login, and instead
          //go to our authenticated state
          var params = { reload: true };
          deferred.resolve($state.target('home', undefined, params));
        }).catch(function() {
          //we're not signed in, so continue to login.**
          deferred.resolve(); 
        });
    
        return deferred.promise;
      });
    }]);
    

    配置看起来像这样:

    $stateProvider
    .state('login', {
      url: '/login'
      // + some template/controller/resolve...
    })
    .state('home', {
      url: '/home'
      // + some template/controller/resolve...
    })
    

    这里是认证工厂

    app.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
      return $firebaseAuth();
    }]);
    

    onBefore 的文档可以在 here 找到。

    【讨论】:

    • 感谢您抽出时间回答@Vincent。一切正常,虽然我在应用程序中有多个需要身份验证的页面,所以你把$transitions.onBefore({to: 'patents.**', from: '**'} 放在哪里,我如何有多个状态将用户返回到登录页面?
    • 忽略我。阅读文档。感谢您的帮助
    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2022-01-05
    • 2017-03-24
    相关资源
    最近更新 更多