如何将 angularfire 登录对象移动到服务文件

How to move the angularfire log in object to a service file

我希望能够在我的网站上全局使用登录对象。我想知道如何将对象移动到服务并利用它来检查登录。这是我的登录控制器:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
     $scope.login = function() {
      $scope.authData = null;
      $scope.error = null;

      userAuth.$signInWithEmailAndPassword($scope.loginemail, $scope.loginpassword)
      .then(function(authData) {
        $scope.authData = authData;
        console.log(authData);
      }).catch(function(error) {
        $scope.error = error.message;
      });
    };

我的服务是:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
    return $firebaseAuth();
  }

我能够成功登录,但我希望能够在全球范围内使用登录凭据。通过这样做,除非用户经过身份验证,否则我还应该如何阻止某些路由。

如果路由仅供登录用户使用,将他们重定向到登录页面。 如果他们已经登录并尝试访问注册页面,请将他们注销。 如果他们已登录并尝试访问登录页面,则将他们重定向到个人资料页面。

我建议将用户数据存储在服务本身中,而不是将其返回给调用者。例如:

.service('userAuth', ["$firebaseAuth", function($firebaseAuth) {
    var userData;
    this.login = function(loginEmail, loginPassword){
       return $firebaseAuth
       .$signInWithEmailAndPassword(loginEmail, loginPassword)
       .then(function(authData) {
           userData = authData;
       });
    }
    this.getUserData = function(){
       return userData;
    }
  }

并在控制器中使用它:

.controller('LoginCtrl', function ($scope, $location, userAuth) {
     $scope.login = function() {
      $scope.authData = null;
      $scope.error = null;

      userAuth.login($scope.loginemail, $scope.loginpassword)
      .then(function() {
        $scope.authData = userAuth.getUserData();
        console.log($scope.authData);
      }).catch(function(error) {
        $scope.error = error.message;
      });
    };

使用这种方法您可以获得两个好处:

  1. 封装登录逻辑。这样您就可以轻松更改登录名 服务而不会中断应用程序的任何其他部分。

  2. 您可以通过注入 auth 服务并调用 getUserData 函数来访问应用程序任何部分的用户数据。

要防止用户访问特定路线,您可以使用 $routeChangeStart 事件来捕获路线更改以停止导航,然后根据您的业务逻辑重定向到其他路线。