简体   繁体   English

Angular:如何捕获失败的 http.get() 方法的 Http 状态码

[英]Angular: How to catch Http Status Code of a failed http.get() method

I have an http.get() method which tries to query a backend API. Given an Id in Frontend, enable a property in the database (this is handled by the backend) I implemented the http method this way:我有一个 http.get() 方法,它试图查询后端 API。在前端给定一个 Id,启用数据库中的一个属性(这由后端处理)我以这种方式实现了 http 方法:

home.ts主页.ts

this.service.getZ(id).subscribe((event:any)=>console.log(event))

service.ts服务.ts

 getz(id):
    return http.get('url'+id,{reportProgress: true,
   responseType: 'text'
}).

Now I need to catch what http status code the backend is sending as I need this status code (like http 200, http 500) to enable another button in the frontend.现在我需要捕获后端发送的 http 状态代码,因为我需要此状态代码(如 http 200、http 500)以在前端启用另一个按钮。 But for some reason I am just not able to capture the http status in the 'event' variable in the home.ts (as shown above).但出于某种原因,我无法在 home.ts 的“事件”变量中捕获 http 状态(如上所示)。 In console, i get this message: enter image description here在控制台中,我收到此消息:在此处输入图像描述

But I am just enable to extract the http status code into a variable.但我只是能够将 http 状态代码提取到一个变量中。 Any suggestions?有什么建议么?

Because the handler is only invoke call succeeds.因为处理程序只是 invoke 调用成功。 For error there is one more callback.对于错误还有一个回调。 so change your code to:-所以将您的代码更改为:-

this.service.getZ(id).subscribe(
   (event:any)=>console.log(event),
   (err) => console.log(err.statusCode)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM