Firebase身份验证与角度:用户登录

firebaseAuth with Angular: User Login

本文关键字:用户 登录 身份验证 Firebase      更新时间:2023-09-26

我正在使用Angular(1.3.5)和Firebase编写玩具博客程序,目前正在为用户登录部分而苦苦挣扎。

我首先创建了一个 Angular 模块:

var blogApp = angular.module('blogApp', ['ngRoute', 'firebase', 'RegistrationController']);

然后在blogApp之上,我创建了一个名为**注册控制器**的控制器:

blogApp.controller('RegistrationController', function ($scope, $firebaseAuth, $location) {
        var ref = new Firebase('https://myAppName.firebaseio.com');
       // var authLogin = $firebaseAuth(ref);

        $scope.login = function(){
            ref.authWithPassword({
                email: $scope.user.email,
                password: $scope.user.password
            }, function(err, authData) {
                if (err) {
                    $scope.message = 'login error';
                } else {
                    $scope.message = 'login sucessful!';
                }
            });
        }; // login
  });  //RegistrationController

我将login()方法附加到 ng-submit 在我的用户登录表单中,范围为 RegistratinController.

当我单击以提交登录表单时,表单不会做出任何响应,也不会显示任何错误。

登录表单仅在我单击"提交"按钮两次时才有效 - 为什么会这样? 令人困惑

您使用的是 Firebase JavaScript 库,而不是 AngularFire 作为登录方法。

您需要将 Firebase 引用传递到$firebaseAuth绑定中。

var auth = $firebaseAuth(ref);

从那里你可以打电话给auth.$authWithPassword.

    $scope.login = function(){
        auth.$authWithPassword({
            email: $scope.user.email,
            password: $scope.user.password
        }, function(err, authData) {
            if (err) {
                $scope.message = 'login error';
            } else {
                $scope.message = 'login successful!';
            }
        });
    }; // login

AngularFire 是 Firebase Library 的 Angular 绑定,用于处理对象和数组的自动同步。AngularFire还处理何时调用$scope.apply以正确更新视图。

在您的情况下,登录代码在第一次点击时有效,但它不会应用于页面。您可以将此代码包装在 $timeout 中,但最好使用 $firebaseAuth 服务。

感谢用户jacobawenger,感谢他在这里发布的解决方案:

无法在AngularFire 0.9.0中获取新的密码身份验证方法?

这按预期工作:

myApp.controller('RegistrationController', 
    function($scope, $firebaseAuth, $location) {
    var ref = new Firebase('https://myApp.firebaseio.com');
    var simpleLogin = $firebaseAuth(ref);
    $scope.login = function() {
        simpleLogin.$authWithPassword({
            email: $scope.user.email,
            password: $scope.user.password
        }).then(function() {
            $location.path('/mypage');
        }, function(err) {
            $scope.message = err.toString();
        });
    } // login
}); // RegistrationController