成功登录firebase后回调?

时间:2018-04-05 22:29:38

标签: javascript firebase firebase-authentication

我正在尝试将Firebase与大多数纯HTML / CSS / Javascript应用程序一起使用。

我有以下功能来处理登录firebase(来自他们的documentation)。

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

当有人试图登录时,显然会有一个函数被调用来处理错误。

我的问题是我希望在firebase成功登录后立即出现一些逻辑(不仅在登录失败后)。有没有办法做到这一点(比如回调)?

1 个答案:

答案 0 :(得分:4)

docs表示此方法返回firebase.Promise

Promise是异步的,并使用回调then( onSuccess, onFailure )catch( onFailure )进行处理,因此您可以在其中使用逻辑。

遗憾的是,文档没有说明将哪些参数传递给onSuccess方法,但您总是可以尝试:

signInWithEmailAndPassword( email, password )
.then( function onSuccess( ...args ) {
  console.log( 'onSuccess', args );
} )
.catch( function onFailure( err ) {
  console.log( 'onFailure', err );
} );
正如@Herohtar所指出的

编辑并在https://stackoverflow.com/a/39958673/344477中回答看起来使用signInWithEmailAndPassword并不是跟踪auth状态的最佳方式,因为它页面刷新后不会调用&等

跟踪用户是否已登录的最佳方法是onAuthStateChanged方法。