2015-06-09 5 views
1

Я стараюсь следовать базовому руководству по thinkster.io и настраивать на проблемы. https://thinkster.io/learn-to-build-realtime-webapps/ В учебнике используется обесцененный SimpleLogin, поэтому я изменил код, тем не менее, я продолжаю получать ошибку следующим образом.AngularJS - Firebase - Promise Error

TypeError:. Не удается прочитать свойство «наконец» неопределенной на Scope $ scope.register (http://localhost:9000/scripts/controllers/auth.js:9:31)

Я считаю, что проблема с обещанием в моей логике контроллера. Он продолжает возвращаться не определен? Любая помощь будет оценена по достоинству. Я могу добавить больше информации в зависимости от того, что люди думают. Спасибо

SERVICE LOGIC

'use strict'; 

app.factory('Auth', function ($firebaseAuth, $rootScope) { 
    var ref = new Firebase('https://park-reservation.firebaseio.com/'); 
    //var auth = $firebaseSimpleLogin(ref); 

    var Auth = { 
    register: function (user) { 
     return ref.createUser({ 
     email: user.email, 
     password: user.password 
     }, function(error, userData) { 
     if (error) { 
      switch (error.code) { 
      case 'EMAIL_TAKEN': 
       console.log('The new user account cannot be created because the email is already in use.'); 
       break; 
      case 'INVALID_EMAIL': 
       console.log('The specified email is not a valid email.'); 
       break; 
      default: 
       console.log('Error creating user:', error); 
      } 
     } else { 
      console.log('Successfully created user account with uid:', userData.uid); 
     } 
     }); 
    }, 
    login: function (user) { 
     return ref.authWithPassword({ 
     email: user.email, 
     password: user.password 
     }, function(error, authData) { 
     if (error) { 
      console.log('Login Failed!', error); 
     } else { 
      console.log('Authenticated successfully with payload:', authData); 
     } 
     }); 
    }, 
    logout: function() { 
     ref.unauth(); 
    }, 
    resolveUser: function() { 
     return ref.getAuth(); 
    }, 
    signedIn: function() { 
     return !!Auth.user.provider; 
    }, 
    user: {} 
    }; 

    $rootScope.$on('login', function(e, user) { 
    console.log('logged in'); 
    angular.copy(user, Auth.user); 
    }); 
    $rootScope.$on('logout', function() { 
    console.log('logged out'); 
    angular.copy({}, Auth.user); 
    }); 

    return Auth; 
}); 

CONTROLLER LOGIC

app.controller('AuthCtrl', function ($scope, $location, Auth, user) { 
    if (user) { 
    // $location.path('/'); 
    } 

    $scope.register = function() { 
    Auth.register($scope.user).finally(function() { 
     return Auth.login($scope.user).finally(function() { 
     $location.path('/'); 
     }); 
    }); 
    }; 
}); 
+0

CreateUser не возвращает обещание. См. Https://www.firebase.com/docs/web/api/firebase/createuser.html. Вы можете использовать $ q и получить отложенное решение, которое вы разрешили. – laughingpine

+0

это имеет смысл, спасибо –

+0

однако я не совсем понимаю, что дезертировал $ q. Я должен буду читать. Если у кого-нибудь есть что добавить, как использовать $ q и вернуть отложенное, я бы с удовольствием его услышал. В противном случае я это рассмотрю. –

ответ

0

createUser и authWithPassword метод Firebase ничего так призывающую finally метод на неопределенное значение будет сгенерировано сообщение об ошибке не возвращается.

Вы должны добавить новый параметр (функцию обратного вызова) к каждому методу register и login, который должен вызываться после ответа метода Firebase.

Изменение службы

register: function (user, cb) { 
     return ref.createUser({ 
     email: user.email, 
     password: user.password 
     }, function(error, userData) { 
     if (error) { 
      switch (error.code) { 
      case 'EMAIL_TAKEN': 
       cb('The new user account cannot be created because the email is already in use.'); 
       break; 
      case 'INVALID_EMAIL': 
       cb('The specified email is not a valid email.'); 
       break; 
      default: 
       cb('Error creating user:', error); 
      } 
     } else { 
      //Successfully created user account 
      cb(null, userData.uid); 
     } 
     }); 
    }, 
    login: function (user, cb) { 
     return ref.authWithPassword({ 
     email: user.email, 
     password: user.password 
     }, function(error, authData) { 
     if (error) { 
      //Login failed 
      cb(error); 
     } else { 
      cb(null, authData); 
     } 
     }); 
    }, 

Изменение в контроллере

$scope.register = function() { 
    Auth.register($scope.user, function(err, userId) { 
     if (err) { 
     //show error 
     return; 
     } 
     //You can add the userId returned by register method to user object 
     $scope.user.Id = userId; 
     Auth.login($scope.user, function(err, authData) { 
     if (err) { 
      //show error 
      return; 
     } 
     $location.path('/'); 
     }); 
    }); 
    }; 
+0

большое спасибо! –

Смежные вопросы