firebase登录成功后回调?

Cam*_*ron 1 javascript firebase firebase-authentication

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

我获得了以下函数来处理登录 firebase (来自他们的文档)。

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

显然,如果有人尝试登录时发生错误,就会调用一个函数来处理错误。

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

Zil*_*nas 5

文档说这个方法返回一个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 );
} );
Run Code Online (Sandbox Code Playgroud)

正如 @Herohtar 所指出的那样进行编辑并在/sf/answers/2797107141/中回答,看起来使用signInWithEmailAndPassword不是跟踪auth状态的最佳方法,因为它在页面刷新等后不会被调用。

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