首页 > 解决方案 > 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,那么它将起作用(但这不是我需要的)。

标签: javascriptfirebasefirebase-authenticationangularfire2ngxs

解决方案


我认为这是因为您调用了一个异步函数,并且由于您不等待结果,因此 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 };
  }

}

推荐阅读