Angular中如何捕获http.get()方法请求返回的HTTP状态码
要获取HTTP响应状态码,你需要修改Angular HttpClient的请求配置,要求返回完整响应对象而非仅响应体,具体操作如下:
1. 修改service.ts的请求配置
在http.get的第二个参数配置项中新增observe: 'response',告知HttpClient返回完整的HttpResponse对象:
getZ(id) { return http.get('url' + id, { reportProgress: true, responseType: 'text', observe: 'response' // 新增配置项 }) }
小提醒:注意方法名大小写和调用侧保持一致,避免出现未定义方法的报错。
2. 调整home.ts的订阅逻辑
修改后订阅拿到的返回结果包含完整响应信息,成功请求的状态码从next回调的结果中取,错误请求(4xx、5xx等)的状态码从error回调的错误对象中取:
// 定义变量存储状态码 let httpStatusCode: number; this.service.getZ(id).subscribe({ next: (res: any) => { httpStatusCode = res.status; // 2xx类成功状态码在此提取 console.log('状态码:', httpStatusCode); console.log('原返回内容:', res.body); // 这里写按钮状态控制逻辑,例如状态码为200时启用按钮 }, error: (err: any) => { httpStatusCode = err.status; // 4xx、5xx类错误状态码在此提取 console.log('错误状态码:', httpStatusCode); // 错误场景下的按钮控制逻辑写在这里 } })
原理解释
默认情况下Angular HttpClient会直接返回解析后的响应体,不会携带状态码、响应头这类元信息。添加observe: 'response'配置后,接口会返回包含所有响应元信息的HttpResponse对象,其中status字段就是你需要的HTTP状态码。
内容的提问来源于stack exchange,提问作者ripunjoym1998
相关产品推荐
相关产品推荐

