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

Angular中如何在view.html展示密码错误的HttpErrorResponse信息

解决登录错误信息在前端页面的展示问题

嘿,我刚搞定了这个困扰我的问题——之前一直不知道怎么在用户输入错误密码时,把后端返回的错误信息传递到login.component.html里显示出来。现在把我的解决方案分享给大家:

关键实现代码

login.component.ts

在组件中定义一个error变量存储错误信息,然后在登录请求的错误回调里捕获后端返回的错误并赋值给这个变量:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

export class LoginComponent implements OnInit {
  error: string;
  loginUserData = {}

  constructor(private auth: AuthService, private router: Router) { }

  ngOnInit() { }

  loginUser(){
    this.auth.loginUser(this.loginUserData).subscribe(
      res => {
        localStorage.setItem('token', res.token);
        this.router.navigate(['/special']);
      },
      err => {
        if( err instanceof HttpErrorResponse ) {
          // 注意:原代码里的`errLogin`是笔误,实际要使用`err`
          if (err.status === 500) {
            this.error = err.error.message;
          }
        }
      }
    )
  }
}

login.component.html

在页面模板中直接通过插值表达式{{ error }}展示错误信息:

<div class="card-header">
  <h3 class="mb-0">Login</h3>
  <!-- 错误信息会在这里实时显示 -->
  {{ error }}
</div>

实现逻辑说明

当用户输入错误密码,后端返回500状态码的错误响应时,前端会捕获这个Http错误,把后端返回的错误信息赋值给组件的error变量,模板里的插值表达式会自动更新DOM,将错误信息展示给用户。

内容的提问来源于stack exchange,提问作者Valentin Valentyn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:25:26