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

Angular登录校验失败时console打印用户名或密码错误的实现咨询

实现方案

你当前的错误拦截器配置会拦截所有401响应,直接执行登出+页面重载,登录请求返回的401错误会被直接中断,无法传递到登录组件的订阅逻辑中,因此无法捕获错误打印提示。


步骤1:修改错误拦截器,区分登录接口的401响应

登录接口返回401属于凭证错误,不需要执行登出重载逻辑,仅其他业务接口返回401时才代表token失效,需要登出。修改后的拦截器代码如下:

export class ErrorInterceptor implements HttpInterceptor {

    constructor(private authenticationService:AuthenticationService) {}

    intercept(request:HttpRequest<any>, next:HttpHandler) : Observable<HttpEvent<any>> {
        return next.handle(request).pipe(catchError(err => {
            // 请将下方的登录接口路径替换为你的项目实际登录接口地址
            const isLoginRequest = request.url.includes('/api/user/login');
            if (err.status===401 && !isLoginRequest) {
                // 非登录接口的401才执行自动登出逻辑
                this.authenticationService.logout();
                location.reload(true);
            }
            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }
}

步骤2:登录组件添加错误回调,打印提示

在登录请求的订阅逻辑中添加error回调,捕获错误后打印指定提示,同时记得重置loading状态避免按钮一直处于加载状态:

onSubmit() {
    this.submitted=true;
    if (!this.loginForm.valid) {
      console.log("invalid");
      return;
    }
    this.loading=true;
    this.authenticationService.login(this.f.username.value,this.f.password.value)
    .pipe(first())
    .subscribe({
      next : () => {
        //get return url from route parameter or default to '/'
        const returnUrl= this.activatedRoute.snapshot.queryParams['returnUrl'] || '/';
        this.router.navigate([returnUrl]);
      },
      error: () => {
        this.loading = false;
        console.log("The user name or password is incorrect.");
      }
    });
  }

如果需要和后端返回的错误信息对齐,也可以直接打印error回调接收的错误参数。


内容的提问来源于stack exchange,提问作者just askin'

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 13:57:04