Home > OS >  Angular: How to catch Http Status Code of a failed http.get() method
Angular: How to catch Http Status Code of a failed http.get() method

Time:10-06

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:

home.ts

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

service.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. 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). In console, i get this message: enter image description here

But I am just enable to extract the http status code into a variable. Any suggestions?

CodePudding user response:

Because the handler is only invoke call succeeds. 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)
)
  • Related