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

如何获取HTTP请求的响应状态?Angular请求状态获取异常排查

问题分析与解决

第一种写法的问题

你当前的服务代码默认使用observe: 'body'(HttpClient的默认配置),这意味着只有请求成功时会返回响应体数据,错误回调仅在请求触发HTTP错误(比如4xx、5xx状态码)时才执行。如果请求成功(比如200状态),错误回调根本不会运行,自然看不到任何输出;而且成功回调里只能拿到响应体,拿不到状态码。

第二种写法的问题

  1. {observe: response}里的response必须是字符串类型,要加单引号写成{observe: 'response'},否则会被当成变量解析,直接报错。
  2. 你用map把响应流转换成了状态值本身,组件订阅时只能拿到状态码,拿不到原本的响应体数据,和你要同时获取profile和状态的需求冲突。

正确实现方式

方式一:服务返回完整响应,组件自行拆分数据和状态

服务代码:

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

public sendParams(body: any): Observable<HttpResponse<IProfile>> {
  // 注意url不要用反引号包裹变量,直接用this.url即可
  return this.httpClient.post<IProfile>(this.url, body, { observe: 'response' });
}

组件代码:

this.service.sendParams(constConnectBody).subscribe(
  (response: HttpResponse<IProfile>) => {
    this.profile = response.body;
    console.log('响应状态码:', response.status); // 正常获取状态
  },
  (error) => {
    console.log('错误状态码:', error.status); // 请求失败时的状态
  }
);

方式二:服务封装状态和响应体,组件直接接收组合数据

如果想在服务层就把状态和响应体整合好,组件不用处理HttpResponse:
服务代码:

public sendParams(body: any): Observable<{ profile: IProfile; status: number }> {
  return this.httpClient.post<IProfile>(this.url, body, { observe: 'response' }).pipe(
    map(response => ({
      profile: response.body,
      status: response.status
    }))
  );
}

组件代码:

this.service.sendParams(constConnectBody).subscribe(
  (result) => {
    this.profile = result.profile;
    console.log('响应状态码:', result.status);
  },
  (error) => {
    console.log('错误状态码:', error.status);
  }
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:39:16