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

Angular 15中如何获取HTTP请求的状态码?

问题分析与解决方案

1. 获取响应状态码的正确方式

你当前的代码无法拿到状态码,因为Angular HttpClient默认只返回响应体数据。要获取包含状态码的完整响应对象,需要在请求配置中添加observe: 'response'。

修改服务中的getData方法

import { HttpResponse } from '@angular/common/http';

public getData(ano: any, mes: any, glosadas: any, pagina: any): Observable<HttpResponse<any>> {
  const token = this.token.retornaToken();
  const headers = new HttpHeaders({ Authorization: `Bearer ${token}` });

  return this.http.get(`API/?TpoRelatorio=1
&SomenteGlosadas=${glosadas}
&Ano=${ano}
&Mes=${mes}
&Page=${pagina}
&Count=0`, {
    headers,
    observe: 'response' // 关键配置,让请求返回完整的HttpResponse对象
  });
}

2. 修正组件中的todasGuias方法

你的while循环存在异步逻辑问题:subscribe是异步执行的,循环会在所有请求发出前就快速跑完,而且初始时this.listaGuias.TotalPages可能未定义,导致循环逻辑失效。同时要调整CSV生成时机,等所有分页数据获取完成后再导出。

import { forkJoin } from 'rxjs';

todasGuias() {
  // 先获取第一页数据,拿到总页数
  this.homeService.getData(this.ano, this.mes, this.glosadas, 1).subscribe(firstResponse => {
    if (firstResponse.status === 200) {
      const firstPageData = firstResponse.body;
      this.listaGuias = firstPageData.Dados[0];
      this.listaTodasGuias = [this.listaGuias.ResultList];
      
      // 生成其余分页的请求数组
      const pageRequests: Observable<HttpResponse<any>>[] = [];
      for (let page = 2; page <= this.listaGuias.TotalPages; page++) {
        pageRequests.push(this.homeService.getData(this.ano, this.mes, this.glosadas, page));
      }

      // 并行发送所有剩余请求,统一处理结果
      forkJoin(pageRequests).subscribe(allResponses => {
        allResponses.forEach(response => {
          if (response.status === 200) {
            const pageData = response.body;
            this.listaTodasGuias.push(pageData.Dados[0].ResultList);
          }
        });

        // 所有数据获取完成后生成CSV
        const options = {
          fieldSeparator: ',',
          quoteStrings: '"',
          decimalseparator: '.',
          showLabels: true,
          showTitle: true,
          title: 'Consulta',
          useBom: true,
          headers: ['Guia', 'Tipo', 'Protocolo', 'Valor Informado', 'Valor Total', 'Cliente'],
        };
        new ngxCsv(this.listaTodasGuias.flat(), 'Consulta', options); // flat()将二维数组转为一维,适配CSV格式
      });
    }
  });
}

关键说明

  • observe: 'response'配置后,HttpClient会返回HttpResponse<T>类型对象,其中status字段对应HTTP状态码,body字段是原接口返回的响应体数据。
  • 使用forkJoin并行处理多分页请求,确保所有数据加载完成后再生成CSV,避免重复导出的问题。
  • 调整逻辑为先获取第一页数据拿到总页数,再生成后续请求,解决初始TotalPages未定义导致的循环错误。
  • 用flat()处理listaTodasGuias的二维数组,保证导出的CSV内容是一维结构的列表数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:25:36