You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何‘密码错误’提示框始终不显示?Angular登录问题

问题排查与解决方案

核心问题分析

页面不显示密码错误提示,主要是代码里的错误判断逻辑、Observable使用方式以及表单控件状态这几个地方出了问题:


1. 修正Firebase错误代码的判断逻辑

Firebase Auth抛出的错误对象,code属性直接存在于错误实例上,并非嵌套在error.error里。原代码的判断逻辑无法正确匹配auth/invalid-credential,导致密码控件的错误状态未被设置。

修改catchError中的判断逻辑:

catchError((error) => {
  // 直接访问error.code,而非error.error.code
  if (error.code === 'auth/invalid-credential') {
    this.form.controls.password.setErrors({ incorrect: true });
    // 标记密码控件为已触碰,满足HTML的显示条件
    this.form.controls.password.markAsTouched();
  }
  this.handleAuthError(error);
  return of(error);
})

2. 修复Observable的错误调用方式

_authService.login返回的是Observable类型,原代码用await处理Observable属于错误用法,会导致后续pipe操作无法正确捕获错误。直接去掉await,改用链式调用:

// 去掉await,直接调用login方法并链式执行pipe
this._authService.login(this.form.controls.email.value.trim(), this.form.controls.password.value.trim())
  .pipe(
    catchError((error) => {
      // ...修正后的错误处理逻辑
    }),
    tap(response => this._handleLogin(response)),
    finalize(() => this.isLoginInProgress.set(false))
  )
  .subscribe({
    error: (error) => {
      console.error('Login error:', error);
    }
  });

3. 适配OnPush变更检测策略(可选)

如果组件使用了OnPush变更检测策略,设置错误后需要手动触发变更检测,确保页面更新:

  • 先注入ChangeDetectorRef:
    constructor(private cdr: ChangeDetectorRef) {}
    
  • 在设置错误后调用检测方法:
    this.cdr.detectChanges();
    

完整修正后的onSubmit方法

async onSubmit(): Promise<void> {
  if (this.form.invalid) {
    this.markAllAsTouched();
    return;
  }
  const email = this.form.get('email')!.value;
  const userExists = await this.checkIfUserExists(email);
  this.isLoginInProgress.set(true);
  this.userExists = userExists;
  
  if (userExists) {
    this._authService.login(this.form.controls.email.value.trim(), this.form.controls.password.value.trim())
      .pipe(
        catchError((error) => {
          if (error.code === 'auth/invalid-credential') {
            this.form.controls.password.setErrors({ incorrect: true });
            this.form.controls.password.markAsTouched();
            // 若使用OnPush策略,取消注释下面一行
            // this.cdr.detectChanges();
          }
          this.handleAuthError(error);
          return of(error);
        }),
        tap(response => this._handleLogin(response)),
        finalize(() => this.isLoginInProgress.set(false))
      )
      .subscribe({
        error: (error) => {
          console.error('Login error:', error);
        }
      });
  } else {
    this.isLoginInProgress.set(false);
    this.authError.set(true); 
  }
}

内容的提问来源于stack exchange,提问作者Mohamed Seif Ben Salah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:32:20