如何使用 AngularFire 在 Firebase 中使用路由和用户身份验证?

How to use routing with user authentication in Firebase using AngularFire?

我目前正在尝试使用路由,以便用户在未通过身份验证时被重定向到某个页面,如果他们通过身份验证则重定向到另一个页面。

下面是HTML

<html ng-app="sampleApp">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
    <script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/0.9.1/angularfire.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="SampleCtrl">
    <div ng-show="user">
      <p>Hello, {{ user.facebook.displayName }}</p>
      <button ng-click="auth.$unauth()">Logout</button>
    </div>
    <div ng-hide="user">
      <p>Welcome, please log in.</p>
      <button ng-click="auth.$authWithOAuthPopup('facebook')">Login</button>
    </div>
  </body>
</html>

下面是申请

var app = angular.module("sampleApp", ["firebase"]);

//Generates the $firebaseAuth instance
app.factory("Auth", ["$firebaseAuth", function($firebaseAuth) {
  var ref = new Firebase("https://crowdfluttr.firebaseio.com/");
  return $firebaseAuth(ref);
}]);

//auth is now used in controller 
app.controller("SampleCtrl", ["$scope", "Auth", function($scope, Auth) {
  $scope.auth = Auth;
  $scope.user = $scope.auth.$getAuth();
}])

//redirects to homepage if $requireAuth rejects
app.run(["$rootScope", "$location", function($rootScope, $location) {
  $rootScope.$on("$routeChangeError", function(event, next, previous, error) {
    if (error === "AUTH_REQUIRED") {
      $location.path("/home");
    }
  });
}]);

//use routeProvider to only load HomeCtrl if $waitroAuth Resolves and returns promise
app.config(["$routeProvider", function($routeProvider) {
  $routeProvider.when("/home", {
    controller: "HomeCtrl",
    templateUrl: "views/home.html",
    resolve: {
      "currentAuth": ["Auth", function(Auth) {
        return Auth.$waitForAuth();
      }]
    }
  }).when("/account", {
   //controller only loaded if $requireAuth resolves
    controller: "AccountCtrl",
    templateUrl: "views/account.html",
    resolve: {
      "currentAuth": ["Auth", function(Auth) {
        return Auth.$requireAuth();
      }]
    }
  });
}]);

//returns the authenticated user from currentAuth or null if not logged in
app.controller("HomeCtrl", ["currentAuth", function(currentAuth) {
}]);

app.controller("AccountCtrl", ["currentAuth", function(currentAuth) {
}]);

上面我的应用程序中的某些内容没有意义,因此在用户通过身份验证后将其重定向到其他页面,或者在未通过身份验证时将其重定向到另一个页面。

在这里查看我的代码笔:http://codepen.io/chriscruz/pen/ogWyLJ

此外,这里有一个参考页面供我尝试从中实施:https://www.firebase.com/docs/web/libraries/angular/guide.html#section-routes

您的解决方案非常简单,因此包括 ngRoute 库:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular-route.min.js"></script>

在你的 html 脑袋里。

然后将 ngRoute 作为依赖项包含在您的应用中,因此:

var app = angular.module("sampleApp", ["firebase", "ngRoute"]);

查看 codepen 上的解决方案:http://codepen.io/christiannwamba/pen/jEmegY 也是

祝你好运 此致