在 angularjs 中处理异步行为 firebase

handle asynchronous behavior firebase in angularjs

我正在尝试将我的 firebase 的身份验证放在服务中。但是我偶然发现了程序流程的一些问题。 firebase 的响应比较慢,代码需要等待它完成。

我试图创建一个 promise,但它无法正常工作。 这是我的代码:

//controller.js

articleControllers.controller('AuthController', 
    ['$scope', '$firebaseObject', 'AuthenticationService', 
    function($scope, $firebaseObject, AuthenticationService){


        $scope.login = function() {    
             AuthenticationService.login($scope.loginForm)
            .then(function(result) {
                if(result.error) {
                    $scope.message= result.error.message;
                }
                else {
                    console.log("user");
                }
            });
        };  
    }
 ]);

services.js

myApp.factory('AuthenticationService',
function($firebase, $firebaseAuth, $routeParams, FIREBASE_URL) {

    var auth = new Firebase(FIREBASE_URL);

    var myReturnObject = {

        //user login
        login: function(user) {
            return auth.authWithPassword({
                email: user.loginEmail,
                password: user.loginPassword
            },
            function(error, authData) {
                console.log("hit after .then");
                return {
                    error: error,
                    authData: authData
                }
            });
         }

    };

    return myReturnObject;
});

我已经在我的代码中为 $http get 请求使用了一次承诺。但是对于 firebase 它似乎不起作用。我收到 错误:无法读取 controller.js 中未定义的 属性 'then'。 任何人都知道如何让 angular 等待服务?

记得注入$q.

myApp.factory('AuthenticationService',
function($q, $firebase, $firebaseAuth, $routeParams, FIREBASE_URL) {

    var auth = new Firebase(FIREBASE_URL);

    var myReturnObject = {

        //user login
        login: function(user) {
          return $q(function(resolve, reject) {
            auth.authWithPassword({
                email: user.loginEmail,
                password: user.loginPassword
            }, function authCallback(error, authData) {
              if (error) {
                return reject(error);
              }
              resolve(authData);

            });
          });

         }

    };

    return myReturnObject;
});