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

如何在Angular中校验Java后端服务返回的响应并处理对应逻辑

实现步骤

一、先修正Java后端逻辑(现有代码存在缺陷,会导致前端拿不到自定义错误码)

现有Java Service层有两个问题:

  • 异常捕获后又执行了throw e,会导致Spring MVC直接返回默认错误响应,你封装的带500错误码的Map不会被返回
  • 无数据场景下同时返回了success:true和Error:400,逻辑冲突,前端无法正确判断
  • 原有空判断顺序错误,会触发空指针异常,需要先判断null再判断是否为空

修改后的Java Service代码:

@Override
public Map<String, Object> listValues(Integer startDate, Integer endDate) throws Exception {
    Map<String, Object> response = new HashMap<>();
    List<ValuesDto> list = new ArrayList<ValuesDto>();
    try {
        list = valuesRepository.findByDates(startDate, endDate);
        // 修正空判断顺序,避免空指针
        if (list == null || list.isEmpty()) {
            LOGGER.error("There is not values");
            response.put("success", false);
            response.put("Error", 400);
            response.put("msg", "所选日期范围内无数据");
        } else {
            response.put("success", true);
            response.put("data", list);
        }
    } catch (Exception e) {
        LOGGER.error("An error ocurred", e);
        response.put("success", false);
        response.put("Error", 500);
        response.put("msg", "服务内部错误,请稍后重试");
        // 删掉throw e,否则封装的响应不会返回
    }
    return response;
}

Controller层无需修改,保持原有逻辑即可。

二、修改Angular Service层代码

原有代码定义的返回类型为ValuesDTO[],和后端实际返回的带状态码、数据字段的结构不匹配,需要先定义统一响应接口:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ValuesDto } from '../Models/ValoresDTO';

// 定义后端统一响应结构
export interface ApiResponse {
  success: boolean;
  Error?: number;
  msg?: string;
  data?: ValuesDto[];
}

@Injectable({
  providedIn: 'root'
})
export class ConsultValuesService {

  constructor(private http: HttpClient) { }
  Url = 'http://localhost:8080/consultValues';

  consultValues(startDate:any, endDate:any){
    // 修改返回类型为刚定义的ApiResponse
    return this.http.get<ApiResponse>(this.Url+ `?startDate=${startDate}&endDate=${endDate}`);
  }
}

三、修改Component层逻辑,增加响应校验和提示

原有代码存在参数传错的问题,两个入参都传了endDate,需要修正,同时在回调里增加状态判断和Swal提示逻辑:

// 表格绑定的变量,对应响应里的data字段
modelConsultValues: ValuesDto[] = [];

getValuesDB() {
  if (this.valuesForm.valid) {
    // 修正参数:第一个是startDate,第二个是endDate,之前传参错误
    this.service.consultValues(this.startDate, this.endDate).subscribe({
      next: (res: ApiResponse) => {
        // 先判断业务请求是否成功
        if (res.success) {
          this.modelConsultValues = res.data || [];
        } else {
          // 根据错误码弹出对应提示
          if (res.Error === 400) {
            Swal.fire({
              icon: 'warning',
              text: res.msg || '所选日期范围内无数据'
            })
          } else if (res.Error === 500) {
            Swal.fire({
              icon: 'error',
              text: res.msg || '服务出错,请稍后重试'
            })
          }
          // 错误场景清空表格数据
          this.modelConsultValues = [];
        }
      },
      // 处理网络异常、跨域、后端未捕获的异常等非业务错误场景
      error: (err) => {
        console.error(err);
        Swal.fire({
          icon: 'error',
          text: '请求失败,请检查网络或联系管理员'
        })
        this.modelConsultValues = [];
      },
      complete: () => console.log('Completed')
    });
  } else {
    Swal.fire({
      icon: 'error',
      text: 'You must select both dates'
    })
  }
}

四、表格渲染补充

前端HTML表格直接绑定modelConsultValues变量即可,无数据时会自动隐藏表格:

<!-- 表格只在有数据时展示 -->
<table *ngIf="modelConsultValues.length > 0" border="1">
  <thead>
    <tr>
      <th>字段1</th>
      <th>字段2</th>
      <!-- 按需补充其他表头 -->
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let item of modelConsultValues">
      <td>{{item.字段1}}</td>
      <td>{{item.字段2}}</td>
      <!-- 按需补充其他字段渲染 -->
    </tr>
  </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 21:54:03