我正在尝试将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成功登录后立即出现一些逻辑(不仅在登录失败后)。有没有办法做到这一点(比如回调)?
答案 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
方法。