如何使用 AngularFire 在 Firebase 中将路由与用户身份验证结合使用



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

下面是一个

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"]);

在代码笔上查看解决方案:http://codepen.io/christiannwamba/pen/jEmegY 也是

好运和问候

相关内容

最新更新