如何使用Firebase v3保护Angular路线?

时间:2016-10-03 19:55:41

标签: angularjs firebase firebase-authentication angularfire

我想使用Firebase V3,AngularJS和ui.router保护我网站上的各种路线。

This看起来像是一个类似的问题。我已经按照SO帖子中的步骤进行了操作,但它不适用于我。

我期待发生的事情: 单击FAQ链接时,如果已注销,我应转发到登录页面,并在登录时显示FAQ页面。

实际发生的事情: 常见问题页面根本无法访问。登录没有任何区别。登出时它也不会将我转发到登录页面。

我在run函数中收到此错误。

ReferenceError: Firebase is not defined(…)       

我在页面上包含了AngularFire,如果我不这样做,即使从依赖项数组中删除Firebase,也会出现模块注入错误。

var app = angular.module('app', ['ui.router', 'firebase']);
app.constant('FirebaseDatabaseUrl', 'https://myfbdb.firebaseio.com');
app.config(function($stateProvider, $urlRouterProvider, $firebaseRefProvider, FirebaseDatabaseUrl) {
    $firebaseRefProvider.registerUrl(FirebaseDatabaseUrl);
// If a route other than status is requested,
// go to the auth route
//$urlRouterProvider.otherwise('/logintest/login');

$stateProvider
    .state('login', {
        url: '/login',
        templateUrl: 'pages/login.html',
        controller: 'LoginController as login'
    })

    .state('faq', {
        url: '/faq',
        templateUrl: 'pages/faq.html',
        controller: 'FaqController as faq',
        resolve: {
          // controller will not be loaded until $requireSignIn resolves
          "firebaseUser": ["$firebaseAuthService", function($firebaseAuthService) {
            console.log('waitForSignIn')
                    // $waitForSignIn returns a promise so the resolve waits for it to complete
                    return $firebaseAuthService.$waitForSignIn();
            }]
          } 

    })
    .state('about', {
        url: '/about',
        templateUrl: 'pages/about.html',
        controller: 'AboutController as about',
        resolve: {
          // controller will not be loaded until $requireSignIn resolves
          "firebaseUser": ["$firebaseAuthService", function($firebaseAuthService) {
            // If the promise is rejected, it will throw a $stateChangeError
            return $firebaseAuthService.$requireSignIn();
          }]
        }           
    })

});



app.controller('FaqController', ['$scope', 'firebaseUser', function($scope, firebaseUser){
console.log('faq')
}]);





app.run(["$rootScope", "$state", function($rootScope, $state) {
  console.log('run');
  $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
 // We can catch the error thrown when the $requireSignIn promise is rejected
 // and redirect the user back to the home page
 if (error === "AUTH_REQUIRED") {
    console.log('redirecting to login page')
   $state.go("login");
 }
 });
  }]);

1 个答案:

答案 0 :(得分:2)

AngularFire版本2.0+与Firebase 3.0兼容。 AngularFire 2.0以下的任何内容都适用于Firebase的旧版本。