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

Angular 9中如何获取API返回的字符串响应并做对应处理

解决方案

核心原因

Angular 内置的 HttpClient 默认会自动将所有响应按JSON格式解析,你遇到的场景是后端在id不存在时返回纯文本字符串,默认解析逻辑会抛出JSON解析错误,所以你无法直接拿到原始的响应文本。

具体实现步骤

  • 第一步:请求时配置响应参数,同时支持读取纯文本和完整响应体
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

// 封装的查询接口方法
getDataById(targetId: number | string) {
  return this.http.get(`/你的接口地址/${targetId}`, {
    observe: 'response', // 获取完整响应对象,包含状态码、响应头、响应体
    responseType: 'text' // 先统一按纯文本格式读取响应体
  }).pipe(
    catchError((err: HttpErrorResponse) => {
      // 非2xx状态码(比如404)的错误场景,直接返回错误文本
      return of({
        isSuccess: false,
        msg: err.error as string
      });
    })
  );
}
  • 第二步:订阅请求时区分处理正常/异常场景
// 调用接口的业务代码
this.getDataById('你传入的id').subscribe(res => {
  // 异常场景,直接展示后端返回的消息
  if ('isSuccess' in res && !res.isSuccess) {
    this.showTip = true;
    this.tipContent = res.msg; // 此处拿到的就是"Sorry this id doesn't exist in our list"字符串
    return;
  }
  // 正常场景,将文本转成JSON格式使用
  try {
    const dataList = JSON.parse(res.body);
    // 处理业务逻辑,比如赋值给页面渲染的列表变量
    this.renderList = dataList;
  } catch (parseErr) {
    // 解析失败的兜底逻辑
    this.showTip = true;
    this.tipContent = '数据解析异常,请稍后重试';
  }
})

注意:如果你的后端对不存在id的请求也返回200状态码,无需走catchError逻辑,直接在正常响应回调中判断返回文本是否为JSON格式即可。

优化方案(更推荐)

建议和后端对齐统一响应格式,无论请求成功/失败都返回JSON结构,比如失败时返回:

{
  "code": 404,
  "message": "Sorry this id doesn't exist in our list",
  "data": null
}

这种场景下你不需要额外处理文本解析,直接在 HttpErrorResponse.error 中就能拿到完整的JSON对象,读取message字段即可展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:24:04