javascript - Firebase 在 NGXS 操作中使用 signInWithEmailAndPassword 时忽略 catch/then
问题描述
我有一个通过电子邮件和密码登录用户的操作:
export class LoginWithCredentials {
static readonly type = '[Auth] Login With Credentials';
}
每当提交登录表单时,我都会发送此操作:
onSubmitLogin() {
this.store.dispatch(LoginWithCredentials);
}
操作处理程序从状态中获取电子邮件和密码并调用firebase.auth().signInWithEmailAndPassword
,如下所示:
@Action(LoginWithCredentials)
loginWithCredentials({getState}: StateContext<AuthStateModel>) {
const {email, password} = getState().forms.login.model;
this.afAuth.auth.signInWithEmailAndPassword(email, password)
.catch(err => console.log(err)); // Should console.log on error
console.log('Should print something');
}
由于某种原因,catch
被忽略了console.log
,应该打印的东西也被忽略了。
我尝试在州外运行此方法,它似乎有效。虽然,我想把这个逻辑放到我的行动中。
PS:
如果我使用signInWithPopup(provider)
而不是signInWithEmailAndPassword
,那么它将起作用(但这不是我需要的)。
解决方案
我认为这是因为您调用了一个异步函数,并且由于您不等待结果,因此 NGXS “考虑操作”(我不知道它在幕后是如何工作的……)。
如果signInWithEmailAndPassword
返回一个承诺试试这个:
@Action(LoginWithCredentials)
async loginWithCredentials({getState}: StateContext<AuthStateModel>) {
const {email, password} = getState().forms.login.model;
await this.afAuth.auth.signInWithEmailAndPassword(email, password)
.catch(err => console.log(err)); // Should console.log on error
console.log('Should print something');
}
无论如何,因为它是异步的,您需要等待答案(成功或失败)来更新您的状态。像这样的东西:
@Action(LoginWithCredentials)
async loginWithCredentials({getState, patchState}: StateContext<AuthStateModel>) {
const {email, password} = getState().forms.login.model;
const loginAnswer = await yourLoginService.login(email, password);
if( loginAnswer === 'success' ) {
patchState( { loggedIn: true };
}
}
推荐阅读
- tableau-api - 从命令行运行流程时出现 TabPy Server 配置错误
- css - TypeScript 编码的菜单和网格无法正确显示
- ios - 为什么 Application Loader 找不到我的图标(错误代码:ERROR ITMS-90023)?
- web-crawler - 从种子 URL 到所有深度的所有子发现 URL 发出自定义元数据
- swift - 如何绑定 ObservableObject?
- php - Laravel CSRF 漏洞
- c++ - exitprompt.cpp:268:22:错误:将 'const ExitPrompter' 作为 'this' 参数传递会丢弃限定符 [-fpermissive]
- java - QUARKUS - MicroProfile REST 客户端:添加自定义的非映射字段
- python - (图像,掩码)对在语义分割任务中不匹配
- java - Java servlet 应用程序在我的本地电脑上工作,但在我的服务器开发上不工作